package mode.observer.final_; /** * * 创建被观察者的接口,规定要实现的方法 * * */ public interface Subject { /* 增加观察者 */ public void add(Observer observer); /* 删除观察者 */ public void del(Observer observer); /* 通知所有的观察者 */ public void notifyObservers(); /* 自己的操作 */ public void operation(); }
package mode.observer.final_; import java.util.Enumeration; import java.util.Vector; /** * * 实现一个抽象的被观察者,用来实现那些所有的被观察者所共有的方法,属性 * * */ public abstract class AbstractSubject implements Subject { private Vector<Observer> vector = new Vector<Observer>(); @Override public void add(Observer observer) { vector.add(observer); } @Override public void del(Observer observer) { vector.remove(observer); } @Override public void notifyObservers() { Enumeration<Observer> enumo = vector.elements(); while (enumo.hasMoreElements()) { enumo.nextElement().update(); } } }
package mode.observer.final_; public class MySubject extends AbstractSubject { @Override public void operation() { System.out.println("update self"); //完成操作后要主动去通知观察者 notifyObservers(); } }
package mode.observer.final_; /*观察者接口,规定所有观察者都要实现update方法*/ public interface Observer { public void update(); }
package mode.observer.final_; public class Observer1 implements Observer { @Override public void update() { System.out.println("Observer1 has received the message !"); } }
package mode.observer.final_; public class Observer2 implements Observer { @Override public void update() { System.out.println("Observer2 has received the message !"); } }
package mode.observer.final_; public class Test { public static void main(String[] args) { Subject sub = new MySubject(); sub.add(new Observer1()); sub.add(new Observer2()); sub.operation(); } }
原文地址:http://blog.csdn.net/u012613903/article/details/44256913