File tree Expand file tree Collapse file tree 1 file changed +42
-1
lines changed Expand file tree Collapse file tree 1 file changed +42
-1
lines changed Original file line number Diff line number Diff line change 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' )
You can’t perform that action at this time.
0 commit comments