Observer Pattern,即觀察者模式,當存在一對多關係,例如一個對象一有變更,就要自動通知被依賴的所有對象得場景,屬於行爲類的設計模式。設計模式
下面是一個觀察者模式的簡單案例。ide
Observer 定義觀察者的接口,定義須要觀察的對象,已經被通知的接口。BinaryObserver, OctalObserver, HexaObserver 各自實現了 Observer 接口。this
Subject 是被觀察的對象,記錄了觀察該對象的觀察者列表,自身有變更,便可通知觀察者列表中的各個觀察者。spa
代碼實現設計
Observer 接口,定義了被通知的方法,定義了觀察的對象。code
public abstract class Observer { protected Subject subject; public abstract void update(int value); }
BinaryObserver, OctalObserver, HexaObserver 實現了 Observer 接口,實現了具體的被通知方法。server
public class BinaryObserver extends Observer { public BinaryObserver(Subject subject){ this.subject = subject; subject.attach(this); } @Override public void update(int value) { System.out.println("BinaryObserver " + Integer.toString(value, 2)); } }
public class OctalObserver extends Observer { public OctalObserver(Subject subject){ this.subject = subject; subject.attach(this); } @Override public void update(int value) { System.out.println("octal Observer update " + Integer.toString(value, 8)); } }
public class HexaObserver extends Observer { public HexaObserver(Subject subject){ this.subject = subject; subject.attach(this); } @Override public void update(int value) { System.out.println("hexa Observer update " + Integer.toString(value, 16)); } }
Subject 是被觀察的對象,內含一個觀察本對象的觀察者名單htm
public class Subject { private List<Observer> observers = new LinkedList<>(); private int state; public int getState() { return state; } public void setState(int state) { this.state = state; this.notifyAllObservers(); } public void attach(Observer observer){ observers.add(observer); } public void notifyAllObservers(){ for (Observer observer : observers){ observer.update(state); } } }
演示代碼,每次更新 Subject 對象的屬性,Subject 都會通知到觀察它的觀察者對象
public class ObserverPatternDemo { public static void main(){ Subject subject = new Subject(); new BinaryObserver(subject); new OctalObserver(subject); new HexaObserver(subject); subject.setState(17); subject.setState(9); } }
參考資料blog