0%

实现一个观察者模式

实现一个基础当观察者模式,当被观察者变动当时候,通知观察者.

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
32
class Observer {
constructor(name) {
this.name = name;
}
update(updateInfo) {
console.log(`${this.name}更新,更新消息为${updateInfo}`);
}
}

class Observerd {
constructor() {
this.observerList = [];
}
addObserve(observer) {
this.observerList.push(observer);
}

notice(updateInfo = "更新消息") {
for (let observe of this.observerList) {
observe.update(updateInfo);
}
}
}

let fooObserve = new Observer("foo");
let barObserve = new Observer("bar");

let observed = new Observerd();

observed.addObserve(fooObserve);
observed.addObserve(barObserve);
observed.notice("测试消息");