Skip to content

发布订阅设计模式 / Publish-Subscribe

发布订阅设计模式在 JavaScript 中是一种很常见的设计模式。

在对象之间定义一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知。

Code

javascript
class PubSub {
  constructor() {
    // key 为事件名称,value 为订阅该事件的函数数组
    this.subscribers = {};
  }

  // 订阅事件
  subscribe(event, fn) {
    if (!this.subscribers[event]) {
      this.subscribers[event] = [];
    }
    this.subscribers[event].push(fn);
  }

  // 发布事件
  publish(event, ...args) {
    if (!this.subscribers[event]) {
      return;
    }
    this.subscribers[event].forEach((fn) => fn(...args));
  }

  // 取消订阅事件
  unsubscribe(event, fn) {
    if (!this.subscribers[event]) {
      return;
    }
    this.subscribers[event] = this.subscribers[event].filter((subscriberFn) => subscriberFn !== fn);
  }
}

const pubSub = new PubSub();
function test1() {
  console.log('test1');
}
function test2() {
  console.log('test2');
}
pubSub.subscribe('test', test1);
pubSub.subscribe('test', test2);
pubSub.publish('test');
pubSub.unsubscribe('test', test2);
pubSub.publish('test');