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)
  • 相关阅读:
    java-String类
    多线程的细节
    java-多线程的练习----妖,等待唤醒,代码重构,lock到condition
    javascript函数的声明和调用
    表单
    java-多线程的入门_进阶总结
    uboot命令
    u-boot移植 III
    u-boot移植 II
    汇编词典
  • 原文地址:https://www.cnblogs.com/Roxxane/p/14757990.html
Copyright © 2011-2022 走看看