发布-订阅模式
发布-订阅模式,又叫观察者模式,它定义了一种一对多的关系。 让多个订阅者对象同时监听某一个发布者,或者叫主题对象, 这个主题对象的状态发生改变时就会通知所有订阅自己的订阅者对象, 使得它们能够自动更新自己的状态。
主要概念:
- Publisher(发布者/主题对象),当消息发生时负责通知对应的订阅者。
- Subscriber(订阅者),负责接收消息并更新自己的状态。
- type(消息类型),订阅者可以订阅不同类型的消息。
- SubscriberMap(订阅者集合),持有不同 type 的数组,存储有所有订阅者的数组。
- subscribe(订阅),该方法将订阅者添加到 SubscriberMap 中对应的数组中。
- unsubscribe(取消订阅),该方法将订阅者从 SubscriberMap 中对应的数组中删除。
- notify(通知),该方法遍历通知 SubscriberMap 中对应 type 数组中的每个订阅者。
javascript 代码
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
| class Publisher { constructor() { this._subMap = {}; }
subscribe(type, cb) { if (this._subMap[type]) { if (!this._subMap[type].includes(db)) { this._subMap[type].push(cb); } } else { this._subMap[type]= [cb]; } }
unsubscribe(type, cb) { if (!this._subMap[type] || !this._subMap[type].includes(cb)) return; const idx = this._subMap[type].indexOf(cb); this._subMap[type].splice(idx, 1); }
notify(type, ...payload) { if (!this._subMap[type]) return; this._subMap[type].forEach(cb => cb(...payload)); } }
const pub = new Publisher(); pub.subscribe('add', (a, b) => { console.log(a + b); })
pub.subscribe('sub', (a, b) => { console.log(a - b); })
pub.notify('add', 1, 2); pub.notify('sub', 5, 3);
|