【nodejs异步部分复习】2.发布订阅和观察者模式
发布订阅
分为两部分
- on 将注册的函数维护到一个数组中
- emit 将数组中的方法依次执行
1 | let eventCenter = { |
观察者模式(Observer)
观察和被观察之间有关联,观察者需要放在被观察者中,被观察者的状态发生变化需要通知观察者,
内部也是基于发布订阅模式,收集观察者,状态变化后需要通知观察者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
31
32class Subject {
constructor(name) {
this.name = name;
this.state = '';
this.observers = [];
}
attach(o) {
this.observers.push(o);
}
setState(newState) {
this.state = newState;
this.observers.forEach(o => o.update(this))
}
}
class Observer {
constructor(name) {
this.name = name;
}
update(subject) {
console.log(subject.state)
}
}
let a = new Subject('a');
let b = new Observer('b');
let c = new Observer('c');
a.attach(b);
a.attach(c);
a.setState('dsadas')
本文作者: haise
本文地址: https://www.shifeng1993.com/2021/01/02/node_async2/
版权声明: 转载请注明出处!