手动实现观察者模式

# 手动实现观察者模式

观察者模式(基于发布订阅模式) 有观察者,也有被观察者

观察者需要放到被观察者中,被观察者的状态变化需要通知观察者 我变化了 内部也是基于发布订阅模式,收集观察者,状态变化后要主动通知观察者

class Subject {
 // 被观察者 学生
 constructor(name) {
  this.state = '开心的';
  this.observers = []; // 存储所有的观察者
 }

 // 收集所有的观察者
 attach(o) {
  // Subject.prototype.attach
  this.observers.push(o);
 }

 // 更新被观察者 状态的方法
 setState(newState) {
  this.state = newState; // 更新状态
  // this 指被观察者学生
  // 通知观察者 更新它们的状态
  this.observers.forEach(o => o.update(this))
 }
}

class Observer {
 // 观察者 父母和老师
 constructor(name) {
  this.name = name;
 }
 update(student) {
  console.log('当前' + this.name + '被通知了', '当前学生的状态是' + student.state)
 }
}

let student = new Subject('学生'); 

let parent = new Observer('父母'); 
let teacher = new Observer('老师'); 

// 被观察者存储观察者的前提,需要先接纳观察者
student. attach(parent); 
student. attach(teacher); 
student. setState('被欺负了');
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
上次更新: 2022/7/2 上午11:52:50