观察者模式:定义了对象之间的一对多依赖,这样依赖,当一个对象改变状态时,它的所有依赖者都会收到通知并自动更新。
下面举一个具体例子:
两个观察者,BinaryObserver的update将setState传入的整数转换成二进制,OctaObserver则是转成八进制
interface Subject { private List<Observer> observers; public void registerObserver(Observer o); public void removeObserver(Observer o); public void notifyAllObservers(); }
public class ConcreteSubject implements Subject{ private List<Observer> observers = new ArrayList<Observer>(); private int state; public int getState() { return state; } public void setState(int state) { this.state = state; notifyAllObservers(); } public void registerObserver(Observer observer){ observers.add(observer); } public void removeObserver(Observer observer){ int i = observers.indexOf(observer); if(i >= 0) observers.remove(i); } public void notifyAllObservers(){ for (Observer observer : observers) { observer.update(); } } }
abstract Observer { public abstract void update(); }
public class BinaryObserver implements Observer{ Subject subject; public BinaryObserver(Subject subject){ this.subject = subject; this.subject.attach(this); } @Override public void update() { System.out.println( "Binary String: " + Integer.toBinaryString( subject.getState() ) ); } }
public class OctalObserver implements Observer{ Subject subject; public OctalObserver(Subject subject){ this.subject = subject; this.subject.attach(this); } @Override public void update() { System.out.println( "Octal String: " + Integer.toOctalString( subject.getState() ) ); } }
测试代码:
Subject subject = new ConcreteSubject(); Observer o = new OctalObserver(subject); Observer b = new BinaryObserver(subject);
subject.registerObserver(o);
subject.registerObserver(b); subject.setState(15); subject.setState(10);
在Swing中有使用到观察者模式,比如JButton的addActionListener方法。