![](https://img.kancloud.cn/10/b7/10b738ec8a7a974093ab2f1a47494540_543x208.png)
![](https://box.kancloud.cn/b9aa6a63c81949fea14e51760b27d7b4_690x322.png)
~~~
// 主题,接收状态变化,触发每个观察者
class Subject {
constructor() {
this.state = 0
this.observers = []
}
getState() {
return this.state
}
setState(state) {
this.state = state
this.notifyAllObservers()
}
attach(observer) {
this.observers.push(observer)
}
notifyAllObservers() {
this.observers.forEach(observer => {
observer.update()
})
}
}
// 观察者,等待被触发
class Observer {
constructor(name, subject) {
this.name = name
this.subject = subject
this.subject.attach(this)
}
update() {
console.log(`${this.name} update, state: ${this.subject.getState()}`)
}
}
// 测试代码
let s = new Subject()
let o1 = new Observer('o1', s)
let o2 = new Observer('o2', s)
let o3 = new Observer('o3', s)
s.setState(1)
s.setState(2)
s.setState(3)
~~~
![](https://img.kancloud.cn/11/b0/11b01f843c66bcaad2fb29a2407430c9_274x260.png)
![](https://box.kancloud.cn/911865e2f5b06df46c29e75349ea895e_442x363.png)
![](https://box.kancloud.cn/9a0256572bd6b3296618d23343bf575d_647x382.png)
![](https://box.kancloud.cn/50f205ba01f41af745d04be4ab2b012f_785x280.png)
![](https://img.kancloud.cn/9a/2d/9a2d616e7d8f9ecb3eed9648a065b690_595x495.png)
![](https://img.kancloud.cn/04/c3/04c3eacfb6ca25dc7de097fa8ae40174_671x301.png)
![](https://img.kancloud.cn/ca/61/ca61ef1b14877aa7903a43c660108284_545x452.png)
![](https://img.kancloud.cn/b9/85/b9853bab552d984b3d184765f2c9363f_752x143.png)