298 字
1 分钟
观察者模式
观察者模式(Observer Pattern):
优点:实现了对象之间的松耦合,支持广播通信,当一个对象状态改变时,可以通知依赖它的其他对象进行更新。
缺点:可能导致性能问题和内存泄漏,需要合理管理观察者列表。
适用场景:当需要实现对象之间的一对多关系,一个对象的改变需要通知其他多个对象时,可以使用观察者模式。
被观察者在 构造函数 中初始化一个数组,用于存放观察者
被观察者有一个方法通过
forEach
取出观察者,通过观察者中的update
方法进行通知
class Subject {
constructor(name) {
this.state = '开心'
this.name = name
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 + ':' + sub.state);
}
}
let son = new Subject('son')
let father = new Observer('father')
let mother = new Observer('mother')
son.attach(father)
son.attach(mother)
son.setState('不开心')