观察者模式包含发布订阅模式
观察者模式(观察者和被观察者(如果被观察者数据变化了通知观察者观察者和被观察者两者之间是有关系的))
发布订阅
//发布订阅模式
// 发布 -> 中间代理 <- 订阅
function Event(){
this.callbacks = []
}
Event.prototype.on = function (callback){
this.callbacks.push(callback)
}
Event.prototype.emit = function (){
this.callbacks.forEach(fn => {
fn()
});
}
let e = new Event()
e.on(function(){
console.log(222)
})
e.emit()
观察者模式
// 被观察者 我家的狗是否叫了
class Subject {
constructor(name) {
this.name = name
this.observers = []
this.state = '没有叫'
}
// 被观察者要提供一个接受观察者的方法
attach(observer){
// 存放所有的观察者
this.observers.push(observer)
}
setState(newState){
// 更改被观察者的状态
this.state = newState
this.observers.forEach(item => {
item.update(newState,this.name)
})
}
}
class Observer {
constructor(name){
this.name = name
}
update(newState,subName) {
// 用来通知所有的观察者状态更新了
console.log(this.name+'观察到'+subName + newState)
}
}
let dog = new Subject('狗')
let me = new Observer('陈明')
let her = new Observer('qq')
dog.attach(me)
dog.attach(her)
dog.setState('叫了')