您的位置:首页 > 编程语言 > Java开发

java 观察者模式Observable Observer

2016-05-19 15:55 375 查看
被观察者继承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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: