观察者模式
- 发布 & 订阅
- 一对多
示例
- 点咖啡, 点好就坐着等
UML 类图
-
dlUML.png
-
代码
// 主题, 保存状态, 状态变化后触发所有观察者对象
class Subject {
constructor() {
this.state = 0;
this.observers = [];
}
getState() {
return this.state;
}
setState(state) {
this.state = state;
this.notifyAllObservers();
}
notifyAllObservers() {
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()}`);
}
}
// 测试
const s = new Subject();
const o1 = new Observer("o1", s);
const o2 = new Observer("o2", s);
const o3 = new Observer("o3", s);
s.setState(1);
s.setState(2);
s.setState(3);
场景
网页事件绑定
![](https://img.haomeiwen.com/i9433513/c6f6248ed6b2dd68.png)
Promise
![](https://img.haomeiwen.com/i9433513/50b3965c69a1cf7e.png)
![](https://img.haomeiwen.com/i9433513/fd098c2982c5172e.png)
jQuery callbacks
![](https://img.haomeiwen.com/i9433513/b4742e0523d108c0.png)
nodejs 自定义事件
![](https://img.haomeiwen.com/i9433513/6f5f12855568ecff.png)
![](https://img.haomeiwen.com/i9433513/830d0391a00082ac.png)
![](https://img.haomeiwen.com/i9433513/56c110414c51f5f7.png)
![](https://img.haomeiwen.com/i9433513/ac881c46577fd85c.png)
![](https://img.haomeiwen.com/i9433513/a3b53b8dd0edf938.png)
其他场景
- nodejs 中: 处理 http 请求; 多进程通讯
![](https://img.haomeiwen.com/i9433513/1f54576644c2e97c.png)
![](https://img.haomeiwen.com/i9433513/5feab538ee42233b.png)
- vue 和 React 组件生命周期触发
- vue watch
![](https://img.haomeiwen.com/i9433513/665a7a379307e3af.png)
![](https://img.haomeiwen.com/i9433513/071b867f32bd4135.png)
设计原则验证
- 主题和观察者分离, 不是主动触发而是被动监听, 两者解耦
- 符合开放封闭原则
网友评论