前端设计模式--观察者模式和发布订阅模式

【1】观察模式

理解: 观察者模式有两个主要的特点
1、观察者通过继承基类将自己注册到目标对象上(发布者)
2、目标对象(发布者)提供了维护观察者的一系列方法(增、删、遍历执行)

// 这种模式中 只有两个角色 1. 订阅者(观察者) 2 发布者 (目标对象)
    // 订阅者直接将事件注册到发布者
    // 发布者参数发生改变直接广播订阅者
    /**
     * 观察者模式我觉最主要的有两点 1 目标对象同时监管观察者 的增删执行
     * 2 观察者通过继承实现基类把自己注册到目标对象
    */
    class Observer{
      constructor(fn) {
        this.update = fn;
      }
    }
    class SubjectDish{
      constructor() {
        this.observerList = [];
      } 
      submit(observer) {
        console.log('--添加订阅' + observer.name);
        this.observerList.push(observer);
      }
      unsubmit(observer) {
        this.observerList.fliter(ob => {
          console.log('---取消订阅'+ observer.name);
          return ob !== observer;
        })
      }
      notify () {
        this.observerList.map(ob => ob.update());
      }
      onDishChange() {
        setTimeout(() => {
          this.notify();
        }, 1000)
      }
    }
    const subject = new SubjectDish();
    const obserber1 = new Observer(function() {
      console.log('---加菜');
    });
    const obserber2 = new Observer(function() {
      console.log('---减菜');
    });
    // 菜品模块 订阅者
    subject.submit(obserber1);
    subject.submit(obserber2);
    // 发布者 加菜逻辑 像是服务端
    subject.onDishChange();
观察者模式.png

【2】发布订阅模式

理解:订阅者 -> 事件控制中心 <- 发布者

class EventCenter {
      constructor() {
          this.observer = {};
      }
      on(eventName, observer) {
          this.observer[eventName] = this.observer[eventName] || [];
          this.observer[eventName].push(observer);
      }
      emit(eventName, ...args) {
          this.observer[eventName].map(ob => ob(...args));
      }
      off(eventName) {
          delete this.observer[eventName];
      }
  }
  // eg:
  var observer = new EventCenter();
  // 这个是目标对象(订阅者) 要将一个函数托管到 中间控制器上
  observer.on('addDish', function() {
      console.log('---加菜函数');
  });
  // 事件触发(点了加菜的按钮)(发布者)
  // 发布者告知订阅者加菜了啦(广播)
  setTimeout(function() {
    observer.emit('addDish');
  }, 2000)

发布订阅模式.png

[参考文件] https://www.cnblogs.com/lovesong/p/5272752.html

你可能感兴趣的:(前端设计模式--观察者模式和发布订阅模式)