观察者模式

  • 定义对象间一种一对多的依赖关系,当一个对象改变状态,则所有依赖于它的对象都会得到通知并自动更新
  • 场景: vue的响应式

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Observer {
states: string[] = []
update(state: string) {
this.states.push(state)
}
}

class People {
state: string = ''
observer:Observer
setState(newState:string){
if(this.state !== newState){
this.state = newState
this.notify(this.state)
}
}
notify(state: string){
if(this.observer !== null){
this.observer.update(state)
}
}
setObserver(observer: Observer) {
this.observer = observer
}
}

const observer = new Observer()
const people = new People().setObserver(observer)
people.setState('shit')
console.log(observer.state)

参考链接