2023了,你还不会手写观察者模式吗?

34 阅读1分钟

观察者模式包括观察者(Observer)和被观察者(Subject),被观察者状态发生变化通知每一个观察者

场景想象:爸爸/妈妈观察baby,baby的状态有开心/不开心,当状态发生改变通知观察者

代码实现

//subject ('小宝宝)

class Subject{
  constructor(name,state){
    this.name = name;
    this.state = state;
    this.observer = []//存放观察者
  }
  //收集观察者
  attach(them){
    this.observer.push(them)
  }
  setState(state){
    this.state = state
    this.observer.forEach(them=>{
      them.update(this)
    })
  }

}

//observer ('爸爸或妈妈')

class Observer{
  constructor(name){
    this.name = name
  }
  update(subject){
    console.log(this.name + '观察' + subject.name+'的状态是:' + subject.state)
  }
}

let baby = new Subject('小宝宝','开心')

let father = new Observer('爸爸')
let mather = new Observer('妈妈')
baby.attach(father)
baby.attach(mather)

baby.setState('不开心')
baby.setState('开心')