观察者模式浅析

//儿子
class mySon {
  constructor(name) {
    this.name = name;
    this.status = "笑了";
    this.arr = [];
  }
  //将家长插入监控组
  attach(item) {
    debugger
    this.arr.push(item);
  }
  changeStatus(newStatus) {
    if (newStatus !== this.status) { //变化状态
      this.status = newStatus;
      this.arr.forEach(item => {
        item.updateStatus(newStatus);
      })
    }
  }
}
//家长
class obServer {
  constructor(name) {
    this.name = name;
  }
  updateStatus(status) {
    console.log(this.name + " 接受到了儿子的状态变化:" + status);
  }
}
let dada = new obServer("吧吧");
let mom = new obServer("妈妈");
let grandfather = new obServer("爷爷");

let son = new mySon("儿子");
son.attach(dada);
son.attach(mom);
son.attach(grandfather);
son.changeStatus("da 了");

这个简单的模型从本质上来说还是callback的应用,
1.将监视人加入到儿子的监控人组里
2.当状态发生变化的时候 循环调用监控人组里的监控方法即可实现

你可能感兴趣的:(只要头不秃就要当高级,js设计模式,JS)