阅读量:0
发布订阅模式(Publish-Subscribe Pattern),也称为观察者模式,是一种常用的设计模式,用于对象之间的消息传递。在这个模式中,订阅者(Observer)注册到发布者(Subject),当发布者状态发生变化时,通知所有订阅者。
下面是一个 JavaScript 实现的发布订阅模式:
class PubSub { constructor() { this.subscribers = {}; } // 订阅事件 subscribe(event, callback) { if (!this.subscribers[event]) { this.subscribers[event] = []; } this.subscribers[event].push(callback); } // 取消订阅 unsubscribe(event, callback) { if (!this.subscribers[event]) return; this.subscribers[event] = this.subscribers[event].filter(subscriber => subscriber !== callback); } // 发布事件 publish(event, data) { if (!this.subscribers[event]) return; this.subscribers[event].forEach(callback => callback(data)); } } // 使用示例 const pubSub = new PubSub(); function subscriber1(data) { console.log(`Subscriber 1 received data: ${data}`); } function subscriber2(data) { console.log(`Subscriber 2 received data: ${data}`); } // 订阅事件 pubSub.subscribe('event1', subscriber1); pubSub.subscribe('event1', subscriber2); // 发布事件 pubSub.publish('event1', 'Hello World!'); // 输出: // Subscriber 1 received data: Hello World! // Subscriber 2 received data: Hello World! // 取消订阅 pubSub.unsubscribe('event1', subscriber2); // 发布事件 pubSub.publish('event1', 'Hello again!'); // 输出: // Subscriber 1 received data: Hello again!