Skip to content
On this page

发布 / 订阅设计模式

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

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

代码实现

// class implementation
class PubSub {
  constructor() {
    // key = event name, value = array of callbacks
    this.subscribers = {};
  }
  subscribe(event, fn) {
    // if event is not in subscribers, create it
    if (!this.subscribers[event]) {
      this.subscribers[event] = [];
    }
    // add callback to subscribers
    this.subscribers[event].push(fn);
  }

  publish(event, ...args) {
    // if event is not in subscribers, return
    if (!this.subscribers[event]) {
      return;
    }
    // call all callbacks for event
    this.subscribers[event].forEach((fn) => fn(...args));
  }
  unsubscribe(event, fn) {
    // if event is not in subscribers, return
    if (!this.subscribers[event]) {
      return;
    }
    // remove callback from subscribers
    this.subscribers[event] = this.subscribers[event].filter(
      (subscriberFn) => subscriberFn !== fn
    );
  }
}

// start test code
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');
// end test code