1、观察者模式
class Subject {
constructor() {
this.observers = [];
}
add (observe) {
this.observers.push(observe);
}
remove(observer) {
this.observers = this.observers.filter(item => item !== observer);
}
notify() {
this.observers.forEach(item => item.updata());
}
}
class Observer {
constructor(name) {
this.name = name;
}
updata() {
console.log('name', this.name);
}
}
const stu = new Subject();
const observer = new Observer('康健');
stu.add(observer);
stu.notify();
stu.remove(observer);
2、发布订阅模式
const PubSub = {
meaasge: {},
publish(type, data) {
if (!this.meaasge[type]) {
return;
}
else {
this.meaasge[type].forEach(item => item(data));
}
},
subscribe(type, cb) {
if (!this.meaasge[type]) {
this.meaasge[type] = [cb];
}
else {
this.meaasge[type].push(cb);
}
}
}
function testA(data) {
console.log('testA', data);
}
function testB() {
console.log('testB', data);
}
PubSub.subscribe('AAA' ,testA);
PubSub.subscribe('BBB' ,testB);
PubSub.publish('AAA', testA('my name is TestA'));
PubSub.publish('BBB', testA('my name is TestB'));