设计模式-观察者、发布订阅模式

167 阅读1分钟

观察者模式

观察者(Observer): 观察者对象,提供监听目标对象更新后的事件。
目标对象(Subject): 被观察的主体,可新增、删除观察者,可通知所有观察者更新。 目标对象和观察者对象时一对多的关系。

class Observer {
    constructor(name) {
        this.name = name
    }
    update() {
        console.log(this.name + ',you should update!')
    }
}
class Subject {
    constructor() {
        this.observers = []
    }
    add(observer) {
        this.observers.push(observer);
    }
    remove(observer) {
        const index = this.observers.findIndex((v) => v === observer);
        this.observers.splice(index, 1);
    }
    notify() {
        this.observers.forEach((v) => {
            v.update();
        })
    }
}
// 初始化一个目标对象
const subject = new Subject();
// 初始化两个观察者
const observer1 = new Observer('观察者1');
const observer2 = new Observer('观察者2');
subject.add(observer1);
subject.add(observer2);
// 目标对象更新,通知观察者
subjects.notify();

发布订阅模式

通过第三方事件中心来调度:

const eventEmitter = {
  map: new Map(),
  // 订阅
  on(key, cb) {
    if (this.map.has(key)) {
      this.map.get(key).push(cb);
    } else {
      this.map.set(key, [cb]);
    }
  },
  // 发布
  emit(key, data) {
    this.map.get(key).forEach((v) => {
      v(data);
    });
  },
};
// 订阅下班事件
eventEmitter.on("xiaban", (e) => {
  console.log("下班咯", e);
});
eventEmitter.on("xiaban", (e) => {
  console.log("我也下班咯", e);
});
// 发布下班事件
eventEmitter.emit("xiaban", { a: 1 });