观察者模式
class Observer {
constructor(name, fn = () => {}) {
this.name = name;
this.fn = fn;
}
}
class Subject {
constructor(state) {
this.state = state;
this.observerList = [];
}
changeState(value) {
this.state = value;
this.observerList.forEach((item) => item.fn(this.state));
}
addObserver(observer) {
this.observerList.push(observer);
}
deleteObserver(observer) {
this.observerList = this.observerList.filter(item !== observer);
}
}
const xz = new Observer("校长", (state) => {
console.log(`因为-${state}-把班主任叫来`);
});
const bzr = new Observer("班主任", (state) => {
console.log(`因为-${state}-把你家长叫来`);
});
const xm = new Subject("学习");
xm.addObserver(xz);
xm.addObserver(bzr);
xm.changeState("睡觉");
发布订阅模式
class Observer {
constructor() {
this.message = {};
}
on(type, fn) {
if (!this.message[type]) {
this.message[type] = [];
}
this.message[type].push(fn);
}
off(type, fn) {
if (!fn) {
delete this.message[type];
} else {
this.message[type] = this.message[type].filter((item) => item !== fn);
}
}
trigger(type) {
if (!this.message[type]) return;
this.message[type].forEach((item) => item());
}
}
const person = new Observer();
person.on("a", handleA);
person.on("a", handleB);
person.on("c", handleC);
person.off("a", handleA);
person.trigger("a");
function handleA() {
console.log("发短信通知");
}
function handleB() {
console.log("发邮件通知");
}
function handleC() {
console.log("其他方式通知");
}