Javascript乱弹设计模式系列 - 观察者模式(Observer)
2010-09-14 13:35:51 来源:WEB开发网调用如下:
var number = new OverloadNumber();
alert("4 - 1 = " + number.Sub(4,1));
alert("++3 = " + number.Add(3));
alert("4 + 6 = " + number.Add(4, 6));
alert("4 + 6 + 5 = " + number.Add(4, 6, 5));
alert(number.Add());
alert("3 - 1 = " + number.Sub(3,1));
alert("--10 = " + number.Sub(10));
alert(number.Add(4, 6, 5, 9)); // Error!参数不匹配
)
--------------------
var IPublisher = new Interface('IPublisher', [['registerSubscriber',1], ['removeSubscriber',1], ['notifySubscribers']]);
所有的依赖者(订阅者)将要注册于它的实现类。
2. 添加ISubscriber.js,它作为系统的订阅者“接口”:
var ISubscriber = new Interface('ISubscriber',[['update',4]]);
3. 现在开始实现我们的IPublisher的具体类,添加OrderData.js,它作为一个订单数据类,让其继承IPublisher的接口:
function OrderData() {
this._subscribers = new Array(); //观察者列表
this.ProductName = ""; //商品名称
this.ProductPrice = 0.0; //商品价格
this.Recommend = 0; //推荐指数
this.productCount = 0; //购买个数
Interface.registerImplements(this, IPublisher);
}
OrderData.prototype = {
registerSubscriber : function(subscriber) { //注册订阅者
this._subscribers.push(subscriber);
},
removeSubscriber : function(subscriber) { //删除指定订阅者
var i = _subscribers.indexOf(subscriber);
if(i > 0)
_subscribers.slice(i,1);
},
notifySubscribers : function() { //通知各个订阅者
for(var i = 0; i < this._subscribers.length; i++)
{
this._subscribers[i].update(this.ProductName, this.ProductPrice, this.Recommend, this.ProductCount);
}
},
SubmitOrder : function(productName,productPrice,recommend,productCount) { //提交订单
this.ProductName = productName;
this.ProductPrice = productPrice;
this.Recommend = recommend;
this.ProductCount = productCount;
this.notifySubscribers();
}
}
Tags:Javascript 乱弹 设计模式
编辑录入:爽爽 [复制链接] [打 印]更多精彩
赞助商链接