观察者模式Observe

2019-08-06  本文已影响0人  TerdShow
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');
上一篇下一篇

猜你喜欢

热点阅读