zoukankan      html  css  js  c++  java
  • 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', '发布');
    

    不同点


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

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

  • 相关阅读:
    [贪心] JZOJ P3757 随机生成器
    [kmp] JZOJ P3756 动物园
    [kmp] JZOJ P3756 动物园
    [记忆化搜索] JZOJ P3767 路径
    [dfs序][线段树][并查集] JZOJ P3766 大融合
    [归并][随机算法] JZOJ P3765 想法
    [枚举][dfs] JOZJ P3749 Fox and City
    [hash] JZOJ P3669 抄卡组
    [dfs][图] 洛谷 P1330 封锁阳光大学
    [并查集]NOIP 2015 Day1 信息传递
  • 原文地址:https://www.cnblogs.com/guolao/p/12111922.html
Copyright © 2011-2022 走看看