2008年4月11日星期五

[设计模式] Observer 观察者



Observer 的目的是一处改动,通过调用Update(),通知所有关联的地方都作相应的变化。当然关联关系是可以增加或者消除的。

Observable 是发生源,当有什么改动,需要通知给相应的对象的时候,通过调用Notify方法,来告诉他所拥有的Observer,而具体的Observer就会通过自己的Update方法,更新自身。

这个原理,有点类似windows中的事件驱动。当发生了某个事件,就会去找对应的事件处理程序,有多少个,就执行多少个。例如C#中这样写
button1.Click += button1_Click;
还可以继续增加事件处理程序
button1.Click += btnAll_Click;
button1.Click += functionButton_Click;
如果某种情况下,不想通知btnAll_Click去执行,那就
button1.Click -= btnAll_Click;
就可以了。

java中的类,下面是这么写的,

java.util.Observable类:

void
addObserver(Observer o)
Adds an observer to the set of observers for this object, provided that it is not the same as some observer already in the set.

protected void
clearChanged()
Indicates that this object has no longer changed, or that it has already notified all of its observers of its most recent change, so that the hasChanged method will now return false.

int
countObservers()
Returns the number of observers of this Observable object.

void
deleteObserver(Observer o)
Deletes an observer from the set of observers of this object.

void
deleteObservers()
Clears the observer list so that this object no longer has any observers.

boolean
hasChanged()
Tests if this object has changed.

void
notifyObservers()
If this object has changed, as indicated by the hasChanged method, then notify all of its observers and then call the clearChanged method to indicate that this object has no longer changed.

void
notifyObservers(Object arg)
If this object has changed, as indicated by the hasChanged method, then notify all of its observers and then call the clearChanged method to indicate that this object has no longer changed.

protected void
setChanged()
Marks this Observable object as having been changed; the hasChanged method will now return true.




java.util.Observer接口:

void
update(Observable o, Object arg)
This method is called whenever the observed object is changed

没有评论: