zoukankan      html  css  js  c++  java
  • 发布订阅模式

    // 主题
    class Dep {
      constructor(callback) {
        this.subs = [] // 主题的订阅者
        this.callback = callback
        // console.log('callback', callback)
      }
    
      // 添加订阅者
      addSub(sub) {
        console.log('sub',sub)
        this.subs.push(sub)
        return this
      }
    
      // 主题更新通知---调用订阅者update,通知所有订阅者
      notify() {
        this.subs.forEach(item => {
        item.update(this.callback)
      });
      }
    }
    
    // 订阅者
    class Sub {
      constructor(val) {
        this.val = val
      }
    
      update(callback) {
        // console.log('update', callback)
        this.val = callback(this.val)
        console.log('更新之后:', this.val)
      }
    }
    
    // 发布者
    class Pub {
      constructor() {
        this.deps = [] // 发布的主题列表
      }
    
      // 添加主题
      addDep(dep) {
        this.deps.push(dep)
      }
    
      // 移除主题
      removeDep(dep) {
        let index = this.deps.indexOf(dep)
        if(index !== -1) {
          this.deps.splice(index, 1)
          return true
        } else {
          return false
        }
      }
    
      // 更新主题
      publish(dep) {
        this.deps.forEach(item => item == dep && item.notify());
      }
    }
    
    // 新建主题, 给主题中加订阅者
    let dep1 = new Dep(item => item * item)
    // console.log(dep1)
    // dep1.addSub(new Sub(1)).addSub(new Sub(2)).addSub(new Sub(3))
    // dep1.addSub(new Sub(1))
    console.log(dep1.addSub(new Sub(1)))
    
    // 新建发布者
    let pub = new Pub()
    // 添加主题
    pub.addDep(dep1)
    
    // 发布者发布,通知这个主题的所有订阅更新
    pub.publish(dep1)
  • 相关阅读:
    SHELL种类,版本及选择
    delete
    ctrl+alt+l:linux 锁屏 win+l:windows锁屏
    inux关于readlink函数获取运行路径的小程序
    网络版shell之网络编程练习篇--telnet服务端
    CentOS 6.5配置nfs服务
    linux操作系下RAR的使用
    BLOB二进制对象(blob.c/h)
    循环队列
    java的System.getProperty()方法能够获取的值
  • 原文地址:https://www.cnblogs.com/Roxxane/p/14757990.html
Copyright © 2011-2022 走看看