发布订阅模式
const fs = require("fs");
let eventObj = {
arr: [],
on(fn) { // 订阅
this.arr.push(fn)
},
emit() { // 发布
this.arr.forEach(fn => fn())
}
}
eventObj.on(() => {
if (Object.keys(obj).length == 2) {
console.log("订阅模式");
}
});
eventObj.on(() => {
if (Object.keys(obj).length == 2) {
console.log("订阅模式成功了");
}
})
let obj = {}
fs.readFile('age.txt', 'utf-8', function (err, data) {
if (err) {
console.log(err);
}
obj.age = data;
eventObj.emit() // 触发
});
fs.readFile('name.txt', 'utf-8', function (err, data) {
if (err) {
console.log(err);
}
obj.name = data,
eventObj.emit() // // 触发
})
观察者模式
class Subject {
constructor(name) {
this.name = name;
this.observer = [];
this.state = "玩耍"
}
attach(o) { // 只要掉了函数就push 进去
this.observer.push(o)
}
setState(newState) { // 只要状态改变了就是通知视图执行
this.state = newState;
this.observer.forEach(o => o.update(this))
}
}
class observer {
constructor(name) {
this.name = name
}
update(bady) {
console.log(bady.name + "跟" + this.name + "说:" + bady.state);
}
};
let bady = new Subject("小宝宝");
let o1 = new observer("爸爸");
let o2 = new observer("妈妈");
bady.attach(o1);
bady.attach(o2);
bady.setState("有人打我")