
说明
1、定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都将得到通知。
2、包括
Subject:主体对象(状态发布者),维护观察者列表,添加或删除观察者。
Observer:观察者,知道自己观察的状态是描述的哪一个对象,提供更新操作。
实例
classSubject{
constructor(){
this.state=0;
this.observers=[];
}
getState(){
returnthis.state;
}
setState(state){
this.state=state;
this.notify();
}
notify(){
this.observers.forEach(observer=>{
observer.update();
})
}
attach(observer){
this.observers.push(observer);
}
}
classObserver{
constructor(name,subject){
this.name=name;
this.subject=subject;
this.subject.attach(this);
}
update(){
console.log(`${this.name}update,state:${this.subject.getState()}`);
}
}
letsub=newSubject();
letobserver1=newObserver('o1',sub);
letobserver2=newObserver('o2',sub);
sub.setState(1);原文来自:https://www.py.cn © 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END


















































暂无评论内容