javaapi中提供了两个类,可以帮助实现观察者模式
Observerable为发布者,Observer为订阅者
订阅者:发布者=1:1/1:n/n:m
import java.util.Observerable;
import java.util.Observer;
public class ObserverDemo {
public static void main(String[] args) {
MyObservable myObservable = new MyObservable();
myObservable.addObserver(new Observer() {
@Override
public void update(Observable o, Object value) {
System.out.println(value);
}
});
myObservable.setChanged();//这里是Observerable源码有个判断,为false直接返回
myObservable.notifyObservers("hello world");
}
public static class MyObservable extends Observable {
public void setChanged() {
super.setChanged();
}
}
}
JDK源码
synchronized (this) {
/* We don't want the Observer doing callbacks into
* arbitrary code while holding its own Monitor.
* The code where we extract each Observable from
* the Vector and store the state of the Observer
* needs synchronization, but notifying observers
* does not (should not). The worst result of any
* potential race-condition here is that:
* 1) a newly-added Observer will miss a
* notification in progress
* 2) a recently unregistered Observer will be
* wrongly notified when it doesn't care
*/
if (!changed)//这里
return;
arrLocal = obs.toArray();
clearChanged();
}