Java观察者设计模式
import java.util.ArrayList; import java.util.List; /** * Created with IntelliJ IDEA. * User: HYY * Date: 13-10-28 * Time: 下午1:34 * To change this template use File | Settings | File Templates. */ /** * 这里使用接口是因为各个观察者可能有各自的独特的方法和属性,因此将其抽象成方法 */ interface Observer { void update(); } interface Subject { void attach(Observer observer); void detach(Observer observer); void notifyObservers(); } class ConcreteObserver implements Observer { private String ObserverName; private Subject subject;//一个指向主题的引用, public ConcreteObserver(String ObserverName, Subject subject) { this.ObserverName = ObserverName; this.subject = subject; if(subject!=null) { subject.attach(this); } } @Override public void update() { //在这个方法中可以通过它,来判断自己关注的数据是否发生变化,并作出相应的行动 System.out.println(ObserverName + " 已经被更新!"); } } class ConcreteSubject implements Subject { List<Observer> observerList; public ConcreteSubject() { this.observerList = new ArrayList<Observer>(); } @Override public void attach(Observer observer) { if (observerList.contains(observer)) { System.out.println("已有该观察者,无需添加!"); } else { observerList.add(observer); } } @Override public void detach(Observer observer) { observerList.remove(observer); } @Override public void notifyObservers() { for (Observer observer : observerList) { observer.update(); } } } public class ObserverTest { public static void main(String[] args) { //初始化4个观察者和一个被观察对象,构造函数自动将观察的对象附上关系 ConcreteSubject subject = new ConcreteSubject(); ConcreteObserver observer1 = new ConcreteObserver("观察者(1)", subject); ConcreteObserver observer2 = new ConcreteObserver("观察者(2)", subject); ConcreteObserver observer3 = new ConcreteObserver("观察者(3)", subject); ConcreteObserver observer4 = new ConcreteObserver("观察者(4)", subject); subject.notifyObservers(); } }
本文出自 无忧之路 - 博客园