Skip to content

观察者模式与发布-订阅

观察者模式

定义了对象间一种一对多的依赖关系,当目标对象 Subject 的状态发生改变时,所有依赖它的对象 Observer 都会得到通知。

js
class Subject {
  constructor() {
    this.observers = [];
  }

  add(observer) {
    this.observers.push(observer);
  }

  remove(observer) {
    const index = this.observers.findIndex((o) => observer.name === o.name);
    this.observers.splice(index, 1);
  }

  notify() {
    this.observers.forEach((observer) => {
      observer.on("hi");
    });
  }
}

class Observer {
  constructor(name) {
    this.name = name;
  }

  on(data) {
    console.log(`【${this.name}】 ` + data);
  }
}

const subject = new Subject();

const zs = new Observer("张三");
const ls = new Observer("李四");

subject.add(zs);
subject.add(ls);
subject.notify();

发布订阅模式

基于一个事件(主题)通道,希望接收通知的对象 Subscriber 通过自定义事件订阅主题,被激活事件的对象 Publisher 通过发布主题事件的方式通知各个订阅该主题的 Subscriber 对象。

js
class EventEmit {
  constructor() {
    this.evtPool = {};
  }

  on(channel, fn) {
    this.evtPool[channel] ||= [];
    this.evtPool[channel].push(fn);
  }

  emit(channel, ...args) {
    this.evtPool[channel].forEach((fn) => {
      fn(...args);
    });
  }

  off(channel) {
    this.evtPool[channel] = [];
  }
}

const eventEmit = new EventEmit();

eventEmit.on("say", (data) => {
  console.log(data + "say A");
});

eventEmit.on("say", (data) => {
  console.log(data + "say B");
});

eventEmit.emit("say", "hello ");

eventEmit.off("say");

eventEmit.emit("say", "hello 1 ");

Released under the MIT License.