最简单的观察者模式
2019-08-17 本文已影响0人
js66
class Subscript{
constructor(name){
this.name = name;
this.state = '心情好';
this.array = [];
}
setState(state){
this.state = state;
this.array.forEach((item)=>{
item.update(state)
})
}
attach(o){
this.array.push(o);
}
}
class Observe{
constructor(name){
this.name = name;
}
update(state){
console.log(this.name+'知道小宝宝'+state)
}
}
let s = new Subscript('我是宝宝');
let o1 = new Observe('爸爸');
let o2 = new Observe('妈妈');
s.attach(o1);
s.attach(o2);
s.setState('心情不好了')