Observer 观察者 行为模式,定义对象的一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于该对象的对象都会得到通知并被自动更新。
Observe模式也很好理解,恩,像flash中的事件侦听,像Rss,向报纸的订阅。
我拿PureMVC来举例吧,PureMVC是跨语言的,现在已经支持很多种语言了。PureMVC中的事件的传递,就没有用到flash本身的事件,而是采用了Observe模式来实现的。
IObserver.as
package org.puremvc.interfaces {
public interface IObserver {
function setNotifyMethod( notifyMethod:Function ):void;
function setNotifyContext( notifyContext:Object ):void;
function notifyObserver( notification:INotification ):void;
function compareNotifyContext( object:Object ):Boolean;
}
}
Observer.as
package org.puremvc.patterns.observer {
import org.puremvc.interfaces.*;
public class Observer implements IObserver {
private var notify:Function;
private var context:Object;
public function Observer( notifyMethod:Function, notifyContext:Object ) {
setNotifyMethod( notifyMethod );
setNotifyContext( notifyContext );
}
public function setNotifyMethod( notifyMethod:Function ):void {
notify = notifyMethod;
}
public function setNotifyContext( notifyContext:Object ):void {
context = notifyContext;
}
private function getNotifyMethod():Function {
return notify;
}
private function getNotifyContext():Object {
return context;
}
public function notifyObserver( notification:INotification ):void {
this.getNotifyMethod().apply(this.getNotifyContext(),[notification]);
}
public function compareNotifyContext( object:Object ):Boolean {
return object === this.context;
}
}
}
PurMVC的订阅者可以是 Command Mediator,发布者可以是 Command Mediator Proxy