Skip to content

Commit 6feb2fc

Browse files
committed
Observer Pattern
1 parent 99990de commit 6feb2fc

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

Example/Observer-Pattern.js

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,42 @@
1-
// 观察者模式(Observer Pattern)
1+
// 观察者模式(Observer Pattern)
2+
3+
class Subject {
4+
constructor () {
5+
this.state = 0
6+
this.observers = []
7+
}
8+
9+
getState () {
10+
return this.state
11+
}
12+
13+
setState (state) {
14+
this.state = state
15+
this.notifyAllObsevers()
16+
}
17+
18+
attach (observer) {
19+
this.observers.push(observer)
20+
}
21+
22+
notifyAllObsevers () {
23+
for (let ele of this.observers.values()) {
24+
ele.update()
25+
}
26+
}
27+
}
28+
29+
class Observer {
30+
constructor (name, subject) {
31+
this.name = name
32+
this.subject = subject
33+
this.subject.attach(this)
34+
}
35+
update () {
36+
console.log(this.name,this.subject.getState())
37+
}
38+
}
39+
40+
let subject = new Subject()
41+
let observer = new Observer('observer 1', subject)
42+
subject.setState('hahaha')

0 commit comments

Comments
 (0)