Skip to main content

观察者模式

观察者模式

let watcher_ids = 0;
let dep_ids = 0;
// 观察者类
class Watcher {
constructor() {
this.id = watcher_ids++;
}
// 观察到变化后的处理
update(ob) {
console.log("观察者" + this.id + `-检测到被观察者${ob.id}${ob.state}`);
}
}

// 被观察者类
class Dep {
constructor() {
this.watchers = [];
this.id = observed_ids++;
this.state = "默认状态";
}
// 添加观察者
addWatcher(watcher) {
this.watchers.push(Watcher);
}
// 删除观察者
removeWatcher(watcher) {
this.watchers = this.watchers.filter((w) => w.id != watcher.id);
}

// 通知自己所有的观察者,ob可以为被观察者自身
notify(ob) {
this.watchers.forEach((watcher) => {
watcher.update(ob);
});
}
}