两个模式的实现结构: segmentfault
观察者模式:观察者(Observer)直接订阅(Subscribe)主题(Subject),而当主题被激活的时候,会触发(Fire Event)观察者里的事件。bash
观察者模式定义了对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,全部依赖于它的对象都将获得通知,并自动更新。观察者模式属于行为型模式,行为型模式关注的是对象之间的通信,观察者模式就是观察者和被观察者之间的通信。ui
发布订阅模式:订阅者(Subscriber)把本身想订阅的事件注册(Subscribe)到调度中心(Topic),当发布者(Publisher)发布该事件(Publish topic)到调度中心,也就是该事件触发时,由调度中心统一调度(Fire Event)订阅者注册到调度中心的处理代码。this
发布订阅模式中,称为发布者的消息发送者不会将消息直接发送给订阅者,这意味着发布者和订阅者不知道彼此的存在。在发布者和订阅者之间存在第三个组件,称为消息代理或调度中心或中间件,它维持着发布者和订阅者之间的联系,过滤全部发布者传入的消息并相应地分发它们给订阅者。spa
代码案例:(猎人发布与订阅任务)prototype
观察者模式:代理
//有一家猎人工会,其中每一个猎人都具备发布任务(publish),订阅任务(subscribe)的功能
//他们都有一个订阅列表来记录谁订阅了本身
//定义一个猎人类
//包括姓名,级别,订阅列表
function Hunter(name, level){
this.name = name
this.level = level
this.list = []
}
Hunter.prototype.publish = function (money){
console.log(this.level + '猎人' + this.name+ '寻求帮助')
this.list.forEach(function(item, index){
item(money)
})
}
Hunter.prototype.subscribe = function (targrt, fn){
console.log(this.level + '猎人' + this.name + '订阅了' + targrt.name)
targrt.list.push(fn)
}
//猎人工会走来了几个猎人
let hunterMing = new Hunter('小明', '黄金')
let hunterJin = new Hunter('小金', '白银')
let hunterZhang = new Hunter('小张', '黄金')
let hunterPeter = new Hunter('Peter', '青铜')
//Peter等级较低,可能须要帮助,因此小明,小金,小张都订阅了Peter
hunterMing.subscribe(hunterPeter, function(money){
console.log('小明表示:' + (money > 200 ? '' : '暂时很忙,不能') + '给予帮助')
})
hunterJin.subscribe(hunterPeter, function(){
console.log('小金表示:给予帮助')
})
hunterZhang.subscribe(hunterPeter, function(){
console.log('小张表示:给予帮助')
})
//Peter遇到困难,赏金198寻求帮助
hunterPeter.publish(198)
复制代码
发布订阅模式:code
//定义一家猎人工会
//主要功能包括任务发布大厅(topics),以及订阅任务(subscribe),发布任务(publish)
let HunterUnion = {
type: 'hunt',
topics: Object.create(null),
subscribe: function (topic, fn){
if(!this.topics[topic]){
this.topics[topic] = [];
}
this.topics[topic].push(fn);
},
publish: function (topic, money){
if(!this.topics[topic])
return;
for(let fn of this.topics[topic]){
fn(money)
}
}
}
function Hunter(name, level){
this.name = name
this.level = level
this.list = []
}
Hunter.prototype.subscribe = function (topic, fn){
console.log(this.level + '猎人' + this.name + '订阅了狩猎' + topic + '的任务')
HunterUnion.subscribe(topic, fn)
}
Hunter.prototype.publish = function (topic, money){
console.log(this.level + '猎人' + this.name + '发布了狩猎' + topic + '的任务')
HunterUnion.publish(topic, money)
}
//猎人工会走来了几个猎人
let hunterMing = new Hunter('小明', '黄金')
let hunterJin = new Hunter('小金', '白银')
let hunterZhang = new Hunter('小张', '黄金')
let hunterPeter = new Hunter('Peter', '青铜')
//Peter等级较低,可能须要帮助,因此小明,小金,小张都订阅了Peter
hunterMing.subscribe('tiger', function(money){
console.log('小明表示:' + (money > 200 ? '' : '不') + '接取任务')
})
hunterJin.subscribe('tiger', function(){
console.log('小金表示:接取任务')
})
hunterZhang.subscribe('tiger', function(){
console.log('小张表示:接取任务')
})
hunterPeter.subscribe('sheep', function(){
console.log('Peter表示:接取任务')
})
//Peter发布了狩猎tiger的任务
hunterPeter.publish('tiger', 198)
//猎人们发布(发布者)或订阅(观察者/订阅者)任务都是经过猎人工会(调度中心)关联起来的,他们没有直接的交流。
复制代码
Sourcecdn