观察者模式
//Subject(小宝宝)
class Subject{
constructor(name){
this.name = name
//小宝宝状态
this.state = '开心'
this.observers = [] //存放观察者
}
//须要将观察者放到本身身上
attach(ther){
this.observers.push(ther)
}
//更新观察者的状态
setState(state){
this.state = state
//循环取出每一个观察者
this.observers.forEach(ther => {
ther.update(this)
})
}
}
class Observer{
constructor(name){
this.name=name
}
//观察小宝宝的状态
update(subject){
console.log(this.name+':'+subject.name+'当前状态是:'+subject.state)
}
}
let baby = new Subject('小宝宝')
let father = new Observer('爸爸')
let mother = new Observer('妈妈')
baby.attach(father)
baby.attach(mother)
baby.setState('不开心')
baby.setState('灰常开心')

发布订阅者模式
//on是订阅 emit是发布
//邮局
let e = {
//存订阅者
_callback:[],
on(callback){
this._callback.push(callback)
},
//发布者
emit(value){
this._callback.forEach(method =>{
method(value)
})
}
}
//订阅
e.on(function(value){
console.log('张三订阅:'+value)
})
e.on(function(value){
console.log('李四订阅:'+value)
})
e.on(function(value){
console.log('王五订阅:'+value)
})
//发布
e.emit('中央日报')

最大区别
- 发布订阅者模式须要有一个调度中心
- 观察者模式能够直接让observer观察到object