观察者模式
2018-08-18 本文已影响0人
hankchang
观察者模式
- 发布 & 订阅
- 一对多
示例
- 点咖啡, 点好就坐着等
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);
场景
网页事件绑定
网页事件绑定.pngPromise
Promise.png Promise2.pngjQuery callbacks
jquery.pngnodejs 自定义事件
node1.png node2.png node3.png node4.png node5.png其他场景
- nodejs 中: 处理 http 请求; 多进程通讯
多进程通讯.png
- vue 和 React 组件生命周期触发
- vue watch
react2.png
设计原则验证
- 主题和观察者分离, 不是主动触发而是被动监听, 两者解耦
- 符合开放封闭原则