观察者模式
观察者模式(有时又被称为发布-订阅模式、模型-视图模式、源-收听者
1、观察者
2、被观察对象
3、撤销观察
package
{
public Class Secretary
{
//同事列表
private var list:Array;
//前台秘书状态
private var action:String;
public function Secretary()
{
list = [];
}
//增加同事
public function Attach(observer:StockObserver):void
{
list.push(observer);
}
//通知
public function notify():void
{
for each(var observer:StockObserver in list)
{
observer.update();
}
}
//前台状态
public function get action():String
{
return action;
}
public function set action(value:String):void
{
action = value;
}
}
}
同事:
package
{
public Class StockObserver
{
private var name:String;
private var sub:Secretary;
public function StockObserver(name:String, sub:Secretary)
{
this.name = name;
this.sub = sub;
}
public function update():void
{
trace(sub.action + name + "关闭股票行情,继续工作!");
}
}
}
主程序:
package
{
public Class Main expends Sprite
{
public function Main()
{
//前台秘书
var tong:Secretary = new Secretary();
// 同事
var tong1:StockObserver = new StockObserver("小童1",tong);
var tong2:StockObserver = new StockObserver("小童2", tong);
// 前台记下两位同事
tong.attach(tong1);
tong.attach(tong2);
//发现老板回来
tong.action = "老板回来了!";
//通知所有已记下的同事
tong.notify();
}
}
}
这只是观察者模式最简单的意思,当然观察者模式肯定离不开代码的解耦是吧。下面是摘自网上的一个观察者视图,希望大家能够明白: