总是把这两个当作同一个模式,但其实是不太一样的,现在重温一下。

观察者模式


观察者直接订阅目标,当目标触发事件时,通知观察者进行更新

简单实现

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

  update() {
    console.log(`${this.name} update`)
  }
}

class subject {
  constructor() {
    this.subs = [];
  }

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

  notify() {
    this.subs.forEach(item => {
      item.update();
    });
  }
}

const sub = new subject();
const ob1 = new Observer('ob1');
const ob2 = new Observer('ob2');

// 观察者订阅目标
sub.add(ob1);
sub.add(ob2);

// 目标触发事件
sub.notify();

发布订阅模式


发布订阅模式通过一个调度中心进行处理,使得订阅者和发布者分离开来,互不干扰。

简单实现

class Event {
  constructor() {
    this.lists = new Map();
  }

  on(type, fn) {
    if (!this.lists.get(type)) {
      this.lists.set(type, []);
    }

    this.lists.get(type).push(fn);
  }

  emit(type, ...args) {
    const arr = this.lists.get(type);
    arr && arr.forEach(fn => {
      fn.apply(null, args);
    });
  }
}

const ev = new Event();

// 订阅
ev.on('msg', (msg) => console.log(msg));

// 发布
ev.emit('msg', '发布');

不同点


其实这两个模式可以说是同一种设计模式的不同实现。

观察者模式是观察者和目标直接进行交互,有耦合性,而发布订阅模式则是通过一个调度中心进行处理,订阅者和发布者互不干扰,进行了解耦。

相关文章:

  • 2021-12-28
  • 2021-08-09
  • 2021-09-11
  • 2022-12-23
  • 2021-11-12
  • 2021-06-09
  • 2021-05-18
猜你喜欢
  • 2022-03-04
  • 2022-12-23
  • 2021-10-17
  • 2021-05-23
  • 2021-12-18
  • 2021-12-28
相关资源
相似解决方案