1.jdk默认对观察者模式提供了支持
被观察着继承Observable
观察者实现Observer接口
被观察者通过调用notifyObservers()方法通知观察者
2.代码实现
/**
Java代码
- * 被观察者
- * Administrator
- *
- */
- public class Watched extends Observable {
- public void count(int num){
- for(;num>=0;num--){
- //通知之前一定要设定setChanged
- this.setChanged();
- //this.notifyObservers();
- //如果需要为观察者传递信息,调用此方法,observer 的update第二个参数就能接受
- this.notifyObservers(num);
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
Java代码
- public class Watcher implements Observer {
- /**
- * arg0:被观查者对象
- * arg1:被观察者传递给观察者信息
- */
- @Override
- public void update(Observable arg0, Object arg1) {
- System.out.println("update....."+arg1);
- }
- }
Java代码
- public class Watcher2 implements Observer {
- @Override
- public void update(Observable arg0, Object arg1) {
- System.out.println("update2....."+arg1);
- }
- }
客户端
Java代码
- public class Main {
- /**
- * @param args
- */
- public static void main(String[] args) {
- Watched watched = new Watched();
- Observer watcher = new Watcher();
- watched.addObserver(watcher);
- Observer watcher2 = new Watcher2();
- watched.addObserver(watcher2);
- /**
- * 那个观察者后被加入,那个观察者update方法就想执行
- */
- watched.count(10);
- }
- }