美文网首页
观察者模式Observe

观察者模式Observe

作者: TerdShow | 来源:发表于2019-08-06 13:31 被阅读0次
    class Subject{
      constructor(name){
        this.name = name;
        this.state = 'a',
        this.stack = []
      }
      attach(observer){
        this.stack.push(observer);
      }
      setState(val){
        this.state = val;
        this.stack.forEach(obs => {
          obs.update(val)
        })
      }
    }
    
    class Observer{
      constructor(name){
        this.name = name;
      }
      update(val){
        console.log(this.name, val);
      }
    }
    
    let sub = new Subject('sub');
    
    let o1 = new Observer('o1');
    let o2 = new Observer('o2');
    
    sub.attach(o1);
    sub.attach(o2);
    
    sub.setState('b');
    

    相关文章

      网友评论

          本文标题:观察者模式Observe

          本文链接:https://www.haomeiwen.com/subject/rveidctx.html