观察者模式基于对象之间的依赖关系。当一个对象(称为主题或被观察者)的状态发生改变时,所有依赖于它的对象(称为观察者)都会被通知并自动更新。
观察者模式主要关注于对象间状态的变化,一个对象的状态改变会引起其他对象的更新。
在Vue中,数据响应式就是一种观察者模式的实现。当数据发生变化时,与之相关的视图会自动更新
思路解析 在Vue中,数据的响应式特性是基于观察者模式实现的,即当数据发生变化时,与之相关的视图会自动更新 订阅者里面主要是有一个update事件用来接收观察者的提示 观察者需要收集订阅者 然后数据变化时触发自身的notify 去调用订阅者的update来完成数据更新
上代码
class Dep {
constructor() {
//声明保存订阅者数组
this.subs = [];
}
//添加订阅者
addSub(sub) {
if (sub && sub.update) {
this.subs.push(sub);
}
}
//移除订阅者
removeSub(sub) {
const index = this.subs.indexOf(sub);
if (index !== -1) {
this.subs.splice(index, 1);
}
}
///通知观察者更新
notify(data) {
this.subs.forEach(sub => {
sub.update(data);
});
}
}
//观察者
class Watcher {
update(data) {
console.log('update11111', data);
}
}
let dep = new Dep();
let watcher1 = new Watcher();
let watcher2 = new Watcher();
dep.addSub(watcher1);
dep.addSub(watcher2);
// 通知观察者,并传递数据
dep.notify('some data');