zoukankan      html  css  js  c++  java
  • js模式-观察者模式

    // 主题,接收状态变化,触发每个观察者
    class Subject {
      constructor() {
          this.state = 0
          this.observers = []
      }
      getState() {
          return this.state
      }
      setState(state) {
          this.state = state
          this.notifyAllObservers()
      }
      attach(observer) {
          this.observers.push(observer)
      }
      notifyAllObservers() {
          this.observers.forEach(observer => {
              observer.update()
          })
      }
    }
    
    // 观察者,等待被触发
    class Observer {
      constructor(name, subject) {
          this.name = name
          this.subject = subject
          this.subject.attach(this)
      }
      update() {
          console.log(`${this.name} update, state: ${this.subject.getState()}`)
      }
    }
    
    // 测试代码
    let s = new Subject()
    let o1 = new Observer('o1', s)
    let o2 = new Observer('o2', s)
    let o3 = new Observer('o3', s)
    
    s.setState(1)
    

    被观察者的状态更改时,观察者执行相对的事情

    观察者和被观察者,耦合度比较小,更改的代码不写在被观察者里面

    一个被观察者可以有多个观察者

    其他应用场景

    1.vue 的 watch 监听 变量的更新

    2. promise then 异步的then 可以有多个then func是被观察者。被观察者更新值,被观察者执行,代码耦合比较小。可以有多个被观察者。

    var func = new Promise((resolve, reject) => {
        resolve('返回值');
    });
    
    func.then(function(){
        console.log("观察者执行....");
    });
    
    func.then(function(){
        console.log("观察者执行....");
    });
    
  • 相关阅读:
    CF140CNew Year Snowmen
    ZR10.1青岛集训三地联考
    CF1228——记一次和紫名失之交臂的CF
    CF1220
    codeforce 382 div2 E —— 树状dp
    codeforce 381 div2
    codeforce 380(div.2)
    Bishops Alliance—— 最大上升子序列
    codeforce 379(div.2)
    模板——BigInteger
  • 原文地址:https://www.cnblogs.com/chenyi4/p/11413920.html
Copyright © 2011-2022 走看看