设计模式-观察者
概念
定义对象一对多的关系,当目标对象发生变化时,通知依赖它的 Observer 对象。
与发布订阅模式区别
观察者: 一对多,接受者被迫接受通知。依赖性强 发布订阅:多了一层中间层(事件调度中心)。解耦
- 目标对象可以 添加、删除、通知 Observer
- Observer 可以接受并处理
- 目标对象发生状态变更时,通知所有 Observer
class Subject {
constructor() {
this.observer = []
}
add(obs) {
this.observer.push(obs)
}
delete(obs) {
const idx = this.observer.findIndex(el => el === obs)
idx > -1 && this.observer.splice(idx, 1)
}
notify() {
this.observer.forEach(el => ('update' in el && el.update()))
}
}
class Observer {
constructor(name) {
this.name = name
}
update() {
console.log('收到:', this.name)
}
}
const sub = new Subject()
sub.add(new Observer('苹果'))
sub.add(new Observer('香蕉'))
sub.notify()