观察者模式
//类似于模型层
class Subject{
constructor() {
this.state = 0;
this.observers = [];
}
getState() {
return this.state;
};
setState(state) {
this.state = state;
this._notifyAllObservers();
};
attach(observer) {
this.observers.push(observer);
};
remove(observer) {
const index = this.observers.find((el) => {
return el == observer;
});
this.observers.splice(index, 1);
};
_notifyAllObservers() {
this.observers.forEach((observer) => {
observer.update();
})
};
}
//类似于视图层
//实例化对象,就会自动把观察者对象放到subject队列里。
class Observer{
constructor(name, subject) {
this.name = name;
this.subject = subject;
this.subject.attach(this);
}
update() {
console.log(`name:${this.name}, state:${this.subject.getState()}`);
}
}
const subject = new Subject();
const observer1 = new Observer('观察者1', subject);
const observer2 = new Observer('观察者2', subject);
const observer3 = new Observer('观察者3', subject);
subject.remove(observer3);
subject.setState(1);
subject.setState(2);
参考
https://www.youtube.com/watch?v=W5OHcEuLIyg