设计模式
发布订阅模式
发布订阅模式 维护一个 事件池,事件池中包含多个事件队列 (数组形式),
发布消息时为指定事件队列发布消息
class Subscribe {
constructor() {
this.event = {};
}
add(eventName, callback) {
if (!this.event[eventName]) {
this.event[eventName] = [];
}
this.event[eventName].push(callback);
}
remove(eventName, callback) {
if (!this.event[eventName]) return;
this.event[eventName] = this.event[eventName].filter(
(ele) => ele !== callback
);
}
publish(eventName, data) {
if (!this.event.hasOwnProperty(eventName)) return;
this.event[eventName].forEach((ele) => {
ele(data);
});
}
}
const subscribe = new Subscribe();
const fn1 = (value) => {
console.log(`gohome-${value}`);
};
const fn2 = (value) => {
console.log(`goshop-${value}`);
};
subscribe.add("home", fn1);
subscribe.add("shop", fn2);
subscribe.publish("home", "eat");
subscribe.publish("shop", "buy");
subscribe.remove("shop", fn2);
subscribe.publish("home", "eat1");
subscribe.publish("shop", "buy1");
观察者模式
观察者模式 被观察者维护一个观察者列表,在被观察者实例状态发生变化时,通知所有观察者(调用观察着所属的函数)。
class Observed {
constructor() {
this.state = 0;
this.observers = [];
}
add(observer) {
this.observers.push(observer);
}
remove(observer) {
const index = this.observers.indexOf(observer);
if (index >= 0) this.observers.splice(index, 1);
}
setState(state) {
this.state = state;
this.notify();
}
notify() {
this.observers.forEach((ele) => {
ele.update(this.state);
});
}
}
class Observer {
constructor(name, observed) {
this.name = name;
this.observed = observed;
this.observed.add(this);
}
update(data) {
console.log(`得到了${data}`);
}
}
const observed = new Observed();
const observer1 = new Observer("obj1", observed);
const observer2 = new Observer("obj2", observed);
observed.setState(1);
策略模式
作用在于替换大量的 if else
使代码维护性更好
const obj = {
a: function () {
},
b: function () {
},
}
obj[变量]()