观察者模式

// 被观察者
class Subject{   // 定义一个对象
    constructor(){  // 构造器---可以实例一个对象
        this.subs = []  // 存储观察者
    }
    addsub(sub){  // 添加观察者
        this.subs.push(sub)
    }
    notify(food){   // 通知观察者
        this.subs.forEach(sub=>{ /// 遍历所有的观察者并且调用update
           sub.update(food)  // 通知观察者来取餐
        })
    }
}

// 观察者---订餐的人
class Observer{
    constructor(name,food){
      this.name = name;
      this.food = food;
    }
    update(food){
      if(food === this.food){
          console.log(this.name + "点的餐:"+food)
      }
    }
}

var sub = new Subject()  // new一个对象会自动调用构造器
var tom = new Observer('张三','鱼香肉丝')
var jack = new Observer('李四','燕窝细粉')
// 将观察者添加到观察列表
sub.addsub(tom)
sub.addsub(jack)
// 通知观察者来取餐
sub.notify("鱼香肉丝")
sub.notify("燕窝细粉")
// 被观察者
class Subject{   // 定义一个对象
    constructor(){  // 构造器---可以实例一个对象
        this.subs = []  // 存储观察者
    }
    addsub(sub){  // 添加观察者
        this.subs.push(sub)
    }
    notify(food){   // 通知观察者
        this.subs.forEach(sub=>/// 遍历所有的观察者并且调用update
           sub.update(food)  // 通知观察者来取餐
        })
    }
}

// 观察者---订餐的人
class Observer{
    constructor(name,food){
      this.name = name;
      this.food = food;
    }
    update(food){
      if(food === this.food){
          console.log(this.name + "点的餐:"+food)
      }
    }
}

var sub = new Subject()  // new一个对象会自动调用构造器
var tom = new Observer('张三','鱼香肉丝')
var jack = new Observer('李四','燕窝细粉')
// 将观察者添加到观察列表
sub.addsub(tom)
sub.addsub(jack)
// 通知观察者来取餐
sub.notify("鱼香肉丝")
sub.notify("燕窝细粉")
原文地址:https://www.cnblogs.com/carry-carry/p/12925759.html