常听到 "观察者模式 vs 发布/订阅模式",
两者分别如何设计,有何不同,请看下文^_^
01
单词解析
观察者模式
Observer : 观察者
Subject: 主题
Subscribe : 订阅
Fire Event: 触发事件
发布订阅模式
Publisher: 发布者
Subscriber: 订阅者
Event Channel: 事件通道(或调度中心)
Subscriber: 订阅
Fire Event : 触发事件
Publish topic :发布主题
Topic: 主题
02
观察者模式 vs 发布/订阅模式
观察者模式:
观察者(Observer)直接订阅(Subscribe)主题(Subject) ,而当主题被激活的时候,会触发(Fire Event)观察者里的事件。
发布订阅模式:
订阅者(Subscriber)把自己想订阅的事件注册(Subscribe)到调度中心(Topic),当发布者(Publisher)发布该事件(Publish topic)到调度中心,也就是该事件触发时,由调度中心统一调度(FireEvent)订阅者注册到调度中心的处理代码。
两者区别:
发布/订阅模式多了一个调度中心
03
示例代码
观察者模式
Subject(主题)
// 宝宝
class Subject{
constructor(name) {
this.name = name;
this.state ="开心";
this.observer = []; //存放观察者
}
// 观察者和宝宝建立联系
attach(ther){
this.observer.push(ther);
}
setState(value){
this.state = value;
this.observer.forEach((item)=>{
item.update(this);
})
}
}
Observer(观察者)
class Observer{
constructor(name) {
this.name = name;
}
update(subject){
console.log(this.name+"观察"+subject.name+",他的心情是"+subject.state);
}
}
使用:
var baby = new Subject("小宝宝");
var father = new Observer("爸爸");
var mother = new Observer("妈妈");
baby.attach(father);
baby.attach(mother);
baby.setState("很开心");
baby.setState("非常开心");
发布订阅模式
Event channel(调度中心)
// on: 订阅 emit: 发布
var ChuBanShe ={ //出版社
_autherArr:[], //所有的订阅者,
on(author){ //订阅
this._autherArr.push(author);
},
emit(value){
//发布的内容通知给所有的订阅者
this._autherArr.forEach(function (item) {
item.tz(value);
})
}
}
Subscribe(订阅)
ChuBanShe.on({name:"张三",msg:"",tz(value){
console.log(this.name+"收到消息:"+value)
}});
ChuBanShe.on({name:"李四",msg:"",tz(value){
console.log(this.name+"收到消息:"+value)
}});
ChuBanShe.on({name:"王麻子",msg:"",tz(value){
console.log(this.name+"收到消息:"+value)
}});
ChuBanShe.on({name:"赵六",msg:"",tz(value){
console.log(this.name+"收到消息:"+value)
}});
Pulish(发布)
ChuBanShe.emit("成都高温天气橙色,注意充电费");
ChuBanShe.emit("下周要下雨");