class Notifier {
constructor(){
this.observerList = []
}
add(obj){
this.observerList.push(obj)
}
remove(obj){
let index = this.observerList.findIndex( (o) => {
return o === obj
})
if(index >= 0) {
this.observerList.splice(index,1)
}
}
notify(){
this.observerList.forEach( (obj) => {
obj.update();
})
}
}
class Observer {
constructor(name){
this.name = name
}
update(){
console.log(this.name,"收到通知")
}
}
let notifier = new Notifier()
let observer1 = new Observer("张三")
let observer2 = new Observer("李四")
notifier.add(observer1)
notifier.add(observer2)
notifier.remove(observer1)
notifier.notify();