观察者模式所做的事情就是在解耦合,让耦合的双方都依赖于抽象,而不是依赖于具体。
这样各自的变化不会影响另一边的变化。
uml:
代码:
通知者:
package observer; import java.util.ArrayList; import java.util.List; public class Subject { private List<Observer> observers = new ArrayList<>(); private String state = null; public String getState() { return state; } public void setState(String state) { this.state = state; } public void attach(Observer observer) { observers.add(observer); } public void detach(Observer observer) { observers.remove(observer); } public void notifyAllObserver() { for(Observer observer : observers){ observer.update(); } } } package observer; public class ConcreteSubject extends Subject { @Override public void notifyAllObserver() { System.out.println("老板回来啦!"); super.notifyAllObserver(); } }
观察者:
package observer; public abstract class Observer { protected Subject subject = null; public Observer(Subject subject) { this.subject = subject; } public abstract void update(); } package observer; public class ConcreteObserver extends Observer{ private String name = null; private String state = null; public ConcreteObserver(String name, String state, Subject subject) { super(subject); this.name = name; } public String getState() { return state; } public void setState(String state) { this.state = state; } @Override public void update() { state = subject.getState(); System.out.print(name + "的新状态是" + state); } }
DEMO:
package observer; public class ObserverDemo { public static void main(String[] args) { Subject subject = new ConcreteSubject(); ConcreteObserver observer = new ConcreteObserver("老王", "看电影", subject); subject.attach(observer); subject.setState("快工作!"); subject.notifyAllObserver(); } }