今天写一个观察者模式的小程序。要求具体主题角色继承自Observable类。然后我在这个具体主题角色类中另外定义了一个方法:
public void go()
{
for (int i = 10; i > 0 ; i--)
{
setChanged(); // 为什么要加这行代码?
notifyObservers(new Integer(i));
}
}
之前我没有加 setChanged(); 导致程序运行的时候不会调用具体观察者类中的update方法。然后加上setChanged();这句之后就可以运行了。具体的运行结果我就不说了,因为我写的小程序不是重点。下面的源码才是,尤其是被我标成红色的那两行。
之后我查看了Observable类的源码。下面是它的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).update(this, arg);
}
这一大串英文还是没让我太明白changed这个成员变量的作用是什么?哪位大侠可以用简洁明了的语言表达下,
|
|