// 发布订阅模式
//定义一个事件对象
const event = {
container:[],
on(fn){
this.container.push(fn);
},
emit(msg){
this.container.forEach(fn=>fn(msg))
}
}
event.on(function(msg){
console.log('小A收到了一条消息' + msg)
})
event.on(function(){
console.log('小A收到了一条消息' + msg)
})
event.emit('马云爸爸又发钱了');
// 观察者模式 基于发布订阅模式 有观察者和被观察者
//定义一个被观察者
class Subject {
constructor(name, state){
this.name = name;//观察者的名字
this.state = state; //观察者 当前的状态
this.container = [];
}
attach(person){
this.container.push(person);
}
setState(newState){
this.state = newState;
this.container.forEach(person=>{
//改变状态 告知观察者
person.update(this)
})
}
}
//定义一个被观察者
class Obverser {
constructor(name){
this.name = name;
}
update(baby){
console.log(this.name+"收到了一条消息,当前小宝贝的状态时"+baby.state)
}
}
let baby = new Subject('小宝贝', '高兴的状态');
let father = new Obverser('爸爸');
let mother = new Obverser('妈妈');
baby.attach(father);
baby.attach(mother);
baby.setState('悲伤的状态');
从以上可以看出发布订阅和观察者模式没有本质的区别,发布订阅模式中的订阅和发布没有必要的联系,但是在观察者模式中 被观察者将观察者保存在实例的数组中 并在状态发生变化主动调用观察者的update方法。