解决的问题:
观察者模式: 主要是用来解决一(被观察者)对多(观察者)的关系。
如教室中,一个老师对多个学生,老师作为被观察者(Subject),而学生作为观察者(Observer),当老师发出指令时,学生就需要做出响应。
定义:
对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
主要结构:
- 一个被观察者,内部需要维护一个与所有观察它的对象数组;
- 多个观察者,内部必须的一个
update
函数,需要在被观察者状态更新后,作出响应。
实现
// 学生类,属于观察者,
class Student {
constructor(name, code) {
this.name = name;
this.code = code;
}
// 当被观察者状态变化时,观察者做出响应
update(object, event) {
console.log(`${object.name}进行了${event},${this.name}收到了该操作`);
}
}
// 被观察对象
class Teacher {
// 保存所有观察者的实例对象
studentList = [];
constructor(name) {
this.name = name;
}
// 将观察对象添加到数组中,
add(student) {
const result = this.studentList.some(item => item.code === student.code);
if (!result) this.studentList.push(student);
}
// 还可以添加移除等...
// 当被观察者状态发生变化时,通过该方法,出发所有观察者状态的变化
notice(event) {
this.studentList.forEach((item) => {
if (item.update) item.update(this, event);
})
}
}
// 多个观察者
const zs = new Student('zs', 111);
const li = new Student('li', 112);
const ww = new Student('ww', 113);
// 被观察者
const luo = new Teacher('罗老师');
luo.add(zs);
luo.add(li);
luo.add(ww);
luo.notice('点名');