观察者模式
//被观察者
function Observed () {
this.state = '不开心';
this.arr = [];
}
//将Observer注册到Observed上
Observed.prototype.attach = function (s) {
this.arr.push(s);
}
//产生新状态
Observed.prototype.setState = function (newState) {
this.state = newState;
this.arr.forEach(fn=>fn.update(this.state))
}
//观察者
function Observer (name,target) {
this.name = name;
this.target = target;
}
//提供一个更新方法,当被观察者的数据发生变化时,需要执行观察者的 update 方法
Observer.prototype.update = function (newState) {
console.log(this.name+'监控到了宝宝的'+newState)
}
let o = new Observed();
let s1 = new Observer('s1',o);
let s2 = new Observer('s2',o);
o.attach(s1);
o.attach(s2);
o.setState('开兴');
//s1监控到了宝宝的开兴
//s2监控到了宝宝的开兴
o.setState('不开兴');
//s1监控到了宝宝的不开兴
//s2监控到了宝宝的不开兴