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

不同點


其實這兩個模式可以說是同一種設計模式的不同實現。

觀察者模式是觀察者和目標直接進行交互,有耦合性,而發布訂閱模式則是通過一個調度中心進行處理,訂閱者和發布者互不干擾,進行了解耦。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM