class Subject{
constructor(name){
this.name = name;
this.state = 'a',
this.stack = []
}
attach(observer){
this.stack.push(observer);
}
setState(val){
this.state = val;
this.stack.forEach(obs => {
obs.update(val)
})
}
}
class Observer{
constructor(name){
this.name = name;
}
update(val){
console.log(this.name, val);
}
}
let sub = new Subject('sub');
let o1 = new Observer('o1');
let o2 = new Observer('o2');
sub.attach(o1);
sub.attach(o2);
sub.setState('b');
网友评论