观察者模式用于一对多的对象关系中,当一个对象被修改时,会自动通知它的依赖对象。java中通过Observable类和Observer接口实现了观察者模式。
例子:
Observer(观察者)
1 2 3 4
| package java.util; public interface Observer { void update(Observable o, Object arg); }
|
Observable(被观察者)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| package java.util; public class Observable { private boolean changed = false; private Vector obs;
public Observable() { obs = new Vector<>(); } public synchronized void addObserver(Observer o) { if (o == null) throw new NullPointerException(); if (!obs.contains(o)) { obs.addElement(o); } } public synchronized void deleteObserver(Observer o) { obs.removeElement(o); } public void notifyObservers() { notifyObservers(null); } 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); } protected synchronized void setChanged() { changed = true; } }
|
创建ObserverA,实现Observer接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| package com.notejava.observer;
import java.util.Observable; import java.util.Observer;
public class ObserverA implements Observer { @Override public void update(Observable o, Object arg) { System.out.println("ObserverA do update"); } }
|
创建ObserverB,实现Observer接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| package com.notejava.observer;
import java.util.Observable; import java.util.Observer;
public class ObserverB implements Observer { @Override public void update(Observable o, Object arg) { System.out.println("ObserverB do update"); } }
|
创建ObserverManager,继承Observable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| package com.notejava.observer;
import java.util.Observable;
public class ObserverManager extends Observable { public ObserverManager() { init(); }
public void init() { this.deleteObservers(); this.addObserver(new ObserverA()); this.addObserver(new ObserverB()); }
public void update() { this.setChanged(); this.notifyObservers(); } }
|
创建Demo演示类
1 2 3 4 5 6 7 8 9 10
| package com.notejava.observer;
public class Demo { public static void main(String\[\] args) { new ObserverManager().update(); } }
|