// 被观察者类
class Subject {
constructor(name) {
this.name = name
this.observers = []
this.state = 'xx'
}
// 被观察者提供订阅观察者方法
attach(observer){
this.observers.push(observer)
}
// 改变被观察者 调用观察者更新方法
setState(newState) {
this.state = newState
this.observers.forEach(o => o.update(newState))
}
}
// 观察者类
class Observer {
constructor(name) {
this.name = name
}
update(newState){
console.log(`${this.name}say: ${newState}`);
}
}
const o1 = new Observer('o1')
const o2 = new Observer('o2')
const s = new Subject('s')
s.attach(o1)
s.attach(o2)
s.setState('yyy')