观察者模式,定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生变化时,会通知所有观察者对象,使他们能够自动更新自己。
Subject
public class Subject { private List<Observer> observers = new ArrayList<Observer>(); public void attach(Observer observer){ observers.add(observer); } public void detach(){ observers.remove(observer); } public void notify(){ for(Observer observer : observers){ observer.update(); } } }
Observer
public class Observer { public void update(){ } }
ConcreteSubject
public class ConcreteSubject extends Subject { private String subjectState; public void setSubjectState(String subjectState){ this.subjectState = subjectState; } public String getSubjectState(){ return this.subjectState; } }
ConcreteObserver
public class ConcreteObserver extends Observer { private String name; private String observerState; public ConcreteSubject subject; public ConcreteObserver(ConcreteSubject subject, String name){ this.subject = subject; this.name = name; } public void setSubject(ConcreteSubject subject){ this.subject = subject; } public ConcreteSubject getSubject(){ return this.subject; } public void update(){ observerState = m_ConcreteSubject.subjectState; System.out.println("观察者"+name+"的新状态是"+observerState); } }
Client
class Client { public static void main(String[] args) { ConcreteSubject s = new ConcreteSubject(); s.attach(new ConcreteObserver(s,"X")); s.attach(new ConcreteObserver(s,"Y")); s.attach(new ConcreteObserver(s,"Z")); s.subjectState = "ABC"; s.notify(); } }
当一个对象的改变需要通知其他对象的时候,并且他不知道有多少个对象需要改变的时候,应该考虑使用观察者模式。