原理
观察者模式是基于发布-订阅模式的。
区别在于发布-订阅模式。发布者和订阅者两者之间无关,通过一个媒介进行交互。
观察者模式有观察者和被观察者。被观察者应该存放着观察者,让被观察者状态发生变化时,要更新自己身上的所有观察者。
如下有个场景,被观察者:宝宝。观察者:父母。当宝宝状态发生变化时,父母接收到状态变化,并且更新。
被观察者
被观察者拥有以下的特征:
- 自己的状态 state
- 观察者队列
- 设置观察者的方法
- 改变自己状态的方法(变更状态并且通知观察者)
观察者
观察者拥有以下的特征:
- 观察者接收到被观察者状态变更后触发更新
实现(ES6)
class Subject {
constructor() {
//存放状态
this.state = '开心';
//存放观察者
this.arr = []
}
attach(observer) {
this.arr.push(observer);
}
setState(newState) {
this.state = newState;
this.arr.forEach(fn => fn.update(newState))
}
}
class Observer {
constructor(name) {
this.name = name;
}
update(state){
console.log(this.name + '-' +state)
}
}
let baby = new Subject();
let father = new Observer('父亲');
let mother = new Observer('母亲');
baby.attach(father);
baby.attach(mother);
baby.setState('大哭');//这时会执行观察者的更新函数
实现(ES5)
function Subject() {
this.state = "安静";
this.arr = [];
}
Subject.prototype.attach = function (observer) {
this.arr.push(observer);
}
Subject.prototype.setState = function (newState) {
this.arr.forEach(observer => observer.update(newState))
}
function Observer(name){
this.name = name;
}
Observer.prototype.update = function(newState){
console.log(this.name + '-' + newState);
}
const baby = new Subject();
const father = new Observer('爸爸');
const mother = new Observer('妈妈');
baby.attach(father);
baby.attach(mother);
baby.setState('大哭');