被观察者继承Observable 观察者实现Observer
过程:
1、调用Observable 的addObserver(Observer) 给被观察者添加观察者
2、在观察者Observer的update(Observable o, Object arg);的方法中做业务处理
3、调用Observable 的setChanged()方法把changed设置为true,调用notifyObservers()方法调用Observer的update方法
notifyObservers源码:
public void notifyObservers(Object arg) {
/*
* a temporary array buffer, used as a snapshot of the state of
* current Observers.
*/
Object[] arrLocal;
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();
}
for (int i = arrLocal.length-1; i>=0; i--)
((Observer)arrLocal[i]).update(this, arg);
}