js 设计模式:观察者和发布订阅模式

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

观察者模式


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

简单实现

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', '发布');

不同点


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

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

猜你喜欢

转载自www.cnblogs.com/guolao/p/12111922.html