定义
定义一对多的对象封装,目标对象状态发生变化,它所有的接受者都会收到通知并做相应的更新。
使用频率:5/5 最高
概要
观察者模式,也就是发布者/订阅者模式,当发布者发布一个通知的时候,订阅者就会收到通知,并调用自己的更新方法,做些什么事情。这种通知是单向的,只能由发布者向订阅者发布通知。
图标说明
示例代码
var Publisher = function () {
this.subscribers = [];
}
Publisher.prototype = {
constructor: Publisher,
addSubscriber: function(subscriber){
this.subscribers.push(subscriber);
},
removeSubscriber: function(subscriber){
var subscribers = this.subscribers,
len = subscribers.length,
i = 0;
for(; i < len; i++){
if (subscribers[i] === subscriber) {
delete subscribers[i];
break;
};
}
},
notifySubscriber: function(message){
var subscribers = this.subscribers,
len = subscribers.length,
i = 0;
for(; i< len; i++){
subscribers[i].receiveMessage(message);
}
}
};
var Subscriber = function(subscriberName, publisher){
this.name = subscriberName;
this.publisher = publisher;
};
Subscriber.prototype = {
constructor: Subscriber,
receiveMessage: function(message){
console.log('I am ' + this.name + ' I receive: ' + message);
}
};
var publisher = new Publisher();
var subUser_001 = new Subscriber('subUser_001', publisher);
var subUser_002 = new Subscriber('subUser_002', publisher);
var subUser_003 = new Subscriber('subUser_003', publisher);
publisher.addSubscriber(subUser_001);
publisher.addSubscriber(subUser_002);
publisher.addSubscriber(subUser_003);
publisher.notifySubscriber('百度推送新闻了');