观察者模式
特点
- 发布&订阅
- 一对多
介绍
-
订阅者只关注自己感兴趣的内容
-
发布者根据不同的订阅者订阅的内容,将对应的结果推送给(已经订阅的)订阅者
-
已经订阅的订阅者:这里说明的是发布者需要将订阅者的注册信息(通知方法)记录下来,以便后续能够直接通知对应的订阅者
-
类似于 ajax 回调函数
- $.ajax(url,data,callback)
- url,data 是提供的数据
- callback 是 ajax 异步返回数据以后,根据特定的结果,做出的特定的相应
- 因为是异步的结果,也许调用这个 ajax 的调用者并不要求立即返回结果,而是希望在
- 返回结果以后,能告知或者直接修改某些数据(此时调用者并不会主动去询问结果)
-
类似于页面上的点击事件
- document 对象发布了一种点击服务,在编程时为某一种页面元素订阅(onclick)这种服务以后,就可以在这个页面元素被点击时,相应对应的
demo
function Subject() {
this.state = "normal";
this.observers = [];
}
Subject.prototype.getState = function () {
return this.state;
};
Subject.prototype.setState = function (state) {
this.state = state;
this.notifyObservers();
};
Subject.prototype.notifyObservers = function () {
for (let observer of this.observers) {
observer.update.call(observer._self, this.state);
}
};
Subject.prototype.attach = function (_self, update) {
this.observers.push({ _self, update });
};
function Observer(name) {
this.name = name;
}
Observer.prototype.on = function (subject, fn) {
subject.attach(this, fn);
};
const s = new Subject();
const o1 = new Observer("o1");
const o2 = new Observer("o2");
s.attach(o1, function (state) {
console.log(`${this.name} get info,new state is ${state}`);
});
s.attach(o2, function (state) {
console.log(`${this.name} get info,new state is ${state}`);
});
s.setState("happy");