design_model(18)observe
1.观察者模式
观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象,这个主题对象在状态发生变化的时,会通知所有观察者对象,使他们能够自动更新自己。
2.实例1
public class ConcreteSubject implements Subject { private int i; public void setI(int i) { this.i = i; } private List<Observer> list = new ArrayList<>(); public void add(Observer observer) { list.add(observer); } public void update() { for (Observer observer : list) { observer.update(i); } } } public class Observer { private int i; public void update(int i) { this.i = i; } public int getI() { return i; } } public interface Subject { } public class Client { public static void main(String[] args) { ConcreteSubject cs = new ConcreteSubject(); cs.setI(3); Observer observer1 = new Observer(); Observer observer2 = new Observer(); cs.add(observer1); cs.add(observer2); cs.update(); System.out.println(observer1.getI()); System.out.println(observer1.getI()); } }
3.实例2
public class ConcreteSubject extends Observable { private int i; public void set(int s) { this.i = s; setChanged(); notifyObservers(i); } public int getI() { return i; } public void setI(int i) { this.i = i; } } public class Observe implements Observer { private int i; @Override public void update(Observable o, Object arg) { this.i = ((ConcreteSubject) o).getI(); } public int getI() { return i; } public void setI(int i) { this.i = i; } } public class Client { public static void main(String[] args) { ConcreteSubject cs = new ConcreteSubject(); Observe observer1 = new Observe(); Observe observer2 = new Observe(); cs.addObserver(observer1); cs.addObserver(observer2); cs.set(3); System.out.println(observer1.getI()); System.out.println(observer1.getI()); } } //源码 public void notifyObservers(Object arg) { Object[] arrLocal; synchronized (this) { if (!changed) return; arrLocal = obs.toArray(); clearChanged(); } for (int i = arrLocal.length-1; i>=0; i--) ((Observer)arrLocal[i]).update(this, arg); }