2023-09-22 00:50:17
发布订阅模式和观察者模式是两种常见的软件设计模式,它们都用于处理对象间的通信,但在实现方式和应用场景上有所不同。以下是对这两种模式的详细比较和总结:
发布订阅模式核心思想:
特点:
代码示例:
class EventEmitter { constructor() { this.subs = {}; // 事件中心 } $on(eventType, handler) { this.subs[eventType] = this.subs[eventType] || []; this.subs[eventType].push(handler); } $emit(eventType) { if (this.subs[eventType]) { this.subs[eventType].forEach(handler => handler()); } }}const em = new EventEmitter();em.$on('a', () => console.log('第一次订阅事件 a'));em.$on('a', () => console.log('第二次订阅事件 a'));em.$emit('a'); // 输出两次订阅的日志观察者模式核心思想:
特点:
代码示例:
class Dep { constructor() { this.subs = []; // 存储观察者 } addSub(sub) { if (sub && sub.update) { this.subs.push(sub); } } notify() { this.subs.forEach(sub => sub.update()); }}class Watcher { update() { console.log('~ ~ ~ update'); }}const dep = new Dep();const watcher = new Watcher();dep.addSub(watcher);dep.notify(); // 输出: ~ ~ ~ update总结在实际应用中,两种模式可以结合使用,以发挥各自的优势。例如,在一个复杂的系统中,可以使用发布订阅模式来处理全局事件,同时使用观察者模式来处理特定组件间的实时通信。