观察者模式Observe

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)