class Observer{
constructor(fn){
this.update = fn
}
}
class Subject {
constructor(){
this.observers = [] //观察者列队
}
addObserver(observer){
this.observers.push(observer) //向观察者列队添加观察者
}
notify(){ //通知所有的观察者,实际上是把观察者的update 都执行了一遍
this.observers.forEach(observer=>{
observer.update()
})
}
}
var subject = new Subject() //被观察者
const update = ()=>{
console.log("被观察者发出通知")
}
var ob1 = new Observer(update);
var ob2 = new Observer(update);
subject.addObserver(ob1);
subject.addObserver(ob2);
subject.notify();
console