观察者模式也称为发布-订阅模式 ,它定义对象间一种一对多的赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都将得到通知。
示例发布者通知工人
class Publisher{
constructor(){
this.workers=[];
}
addWorker(worker){
this.workers.push(worker);
}
subWorker(worker){
this.workers=this.workers.filter((item)=>item!=worker);
}
notify(){
this.workers.forEach((item)=>{
item.action();
});
}
}
class Worker{
constructor(id,name,type){
this.id=id;
this.name=name;
this.type=type;
}
action(){
console.log('this worker : id=',this.id,' name=',this.name,' type=',this.type, ' receive the notify.');
}
};
let p=new Publisher();
let w1=new Worker(1,'a','e');
let w2=new Worker(2,'b','f');
let w3=new Worker(3,'c','g');
let w4=new Worker(4,'d','h');
p.addWorker(w1);
p.addWorker(w2);
p.addWorker(w3);
p.addWorker(w4);
p.notify();
p.subWorker(w3);
p.notify();