-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
44 lines (41 loc) · 789 Bytes
/
index.js
File metadata and controls
44 lines (41 loc) · 789 Bytes
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
33
34
35
36
37
38
39
40
41
42
43
44
/**
* 发布 & 订阅
* 一对多
*/
class Subject {
constructor() {
this.state = 0;
this.observers = [];
}
getState() {
return this.state;
}
setState(state) {
this.state = state;
this.notifyAll();
}
notifyAll() {
this.observers.forEach(observer => {
observer.update();
});
}
attach(observer) {
this.observers.push(observer);
}
}
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 subject = new Subject();
let o1 = new Observer("o1", subject);
let o2 = new Observer("o2", subject);
subject.setState(1);
subject.setState(2);
subject.setState(3);