发布订阅模式和观察者模式的简单实现
发布订阅模式
class PubSub {
constructor() {
this.events = {}
}
publish(type, ...args) {
if(this.events[type] && this.events[type].length > 0) {
this.events[type].forEach(cb => cb(...args))
}
}
subscribe(type, cb) {
this.events[type] = this.events[type] || []
this.events[type].push(cb)
}
cancleSubscrible(type, cb) {
if(!Array.isArray(this.events[type]))return
const index = this.events[type].findIndex(item => item === cb)
this.events[type].splice(index,1)
if(this.events[type].length === 0)delete this.events[type]
}
}
const pubSub = new PubSub()
const handleClick = function() {
console.log('触发了点击事件');
}
pubSub.subscribe('click',handleClick)
pubSub.publish('click')
观察者模式
class Subject {
constructor() {
this.observers = []
}
addObserver(observer) {
this.observers.push(observer)
}
removeObserver(observer) {
const index = this.observers.findIndex(item => item == observer)
this.observers.splice(index, 1)
}
notifyObserver() {
this.observers.forEach(item => {
item.update()
})
}
}
class Observer {
constructor(name, age) {
this.name = name
this.age = age
}
update() {
console.log(`我是${this.name},${this.age}岁`);
}
}
const subject = new Subject()
const p1 = new Observer('zhangsan', 20)
const p2 = new Observer('lisi',22)
subject.addObserver(p1)
subject.addObserver(p2)
subject.notifyObserver()
总结
观察者模式和发布订阅模式都是定义一对多的依赖关系,发布订阅模式相比于观察者模式多了一个事件调度中心,耦合度更低,观察者模式是目标对象维护所有的观察者列表