观察者模式和发布订阅模式
2022-10-12 本文已影响0人
海豚先生的博客
303c1bf20396fa8712b6baf134526fa.png
观察者模式:
class Subject {
constructor(name){
this.name = name;
this.state = '初始值';
this.observers = [];
}
// 收集观察者
collectObservers(observer){
this.observers.push(observer);
}
// 改变状态后,发送给观察者
changeState(state) {
this.state = state;
this.fireObserver(this);
}
// 触发观察者的方法
fireObserver(subject){
this.observers.forEach(function (observer) {
observer.update(subject);
} )
}
}
class Observer {
constructor(name) {
this.name = name;
}
update(subject){
console.log('观察到了');
}
}
s1 = new Subject();
o1 = new Observer();
o2 = new Observer();
s1.collectObservers(o1);
s1.collectObservers(o2);
s1.changeState('改变状态1');
s1.changeState('改变状态2');
订阅-发布模式
let eventEmitter = {};
eventEmitter.list = {};
eventEmitter.on = function (event,fn) {
this.list[event] = this.list[event] || [];
this.list[event].push(fn);
}
eventEmitter.emit = function (event) {
this.list[event].forEach(fn => {
fn()
});
}
eventEmitter.on('event1', () => {
console.log('触发event1');
})
eventEmitter.on('event1', () => {
console.log('触发event11');
})
eventEmitter.on('event2', () => {
console.log('触发event2');
})
eventEmitter.emit('event1');
eventEmitter.emit('event2');