观察者模式是什么东东呢?我先用生活的例子,简单说明一下吧。
① 报社的业务就是出版报纸
② A、B、C三个人想某个报社订阅了报纸,只要他们有新的报纸出版,就会给这三个用户送报纸。只要他们三个一直是这个报社的订户,就会一直收到新的报纸。
③ 当这三个人,其中一个不再想看报纸的时候,取消订阅,他们就不会收到报纸。
④ 只要报社还在运营,就会一直有人向他们订阅报纸或取消报纸。
出版者 + 订阅者 = 观察者模式
观察者模式:定义一个对象之间的一对多依赖,这样一来,当一个对象改变状态时,他的所有依赖者都会收到通知并自动更新。
![这里写图片描述](https://img-blog.csdn.net/20170601144026452?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvV2lsbHNvbl9M/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
其实无论是我那个报社的例子,还是概念。都简单的说明了,观察者模式就是主体一变,对他的依赖就会收到改变的消息。
那代码怎么实现呢?
以下例子不是本人所写,来自:http://www.cnblogs.com/TomXu/archive/2012/03/02/2355128.html
var pubsub = {};
(function(q) {
var topics = {},
subUid = -1;
q.publish = function(topic, args) {
if (!topics[topic]) {
return false;
}
setTimeout(function() {
var subscribers = topics[topic],
len = subscribers ? subscribers.length : 0;
while (len--) {
subscribers[len].func(topic, args);
}
}, 0);
};
q.subscribe = function (topic, func) {
if (!topics[topic]) {
topics[topic] = [];
}
var token = (++subUid).toString();
topics[topic].push({
token: token,
func: func
});
return token;
};
q.unsubscribe = function (token) {
for (var m in topics) {
if (topics[m]) {
for (var i = 0, j = topics[m].length; i < j; i++) {
if (topics[m][i].token === token) {
topics[m].splice(i, 1);
return token;
}
}
}
}
return false;
};
})(pubsub);
pubsub.subscribe('example1', function (topics, data) {
console.log(topics + ": " + data);
});
pubsub.publish('example1', 'hello world!');
pubsub.publish('example1', ['test', 'a', 'b', 'c']);
pubsub.publish('example1', [{ 'color': 'blue' }, { 'text': 'hello'}]);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
如果熟悉 Java api 的人就知道 Java.util 里面其实有观察者模式的包。
观察者实现 Observer 接口,重写 update 方法。
被观察者者继承 Observable 类,调用 setChanged() 和 notifyObservers() 方法。
在这里,我用 js 参考这两个类封装一了个公共的接口。
var Observable = function() {
this.changed = false;
this.obs = [];
};
Observable.prototype.addObserver = function(observer) {
this.obs.push(observer);
};
Observable.prototype.notifyObservers = function(args) {
var arrLocal = this.obs || [];
if (!this.changed || arrLocal.length === 0) {
console.log('被观察者队列中没有数据!');
return;
}
for (var i = 0; i < arrLocal.length; i++) {
arrLocal[i].update.call(arrLocal[i], this, args);
}
};
Observable.prototype.countObservers = function() {
return this.obs.length;
};
Observable.prototype.deleteObservers = function() {
this.obs = [];
};
Observable.prototype.deleteObserver = function(observer) {
var flag = false;
var index = -1;
for (var i = 0; i < this.obs.length; i++) {
if (observer == this.obs[i]) {
flag = true;
index = i;
}
}
if (flag) {
this.obs.splice(index, 1);
}
return flag;
};
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- Observer 接口,因为 javascript 没有接口,所以这里还是使用类
var Observer = function(observable) { };
Observer.prototype.update = function() {
throw new Error('子类实现的方法!');
};
- 调用
这里我使用了 Head First 的例子,气象站。只要气象站测试到温度,湿度的改变,所有的显示气象的公告板都要收到数据,并发生改变。
var WeatherData = function() {
this.temperature = 0;
this.humidity = 0;
this.perssure = 0;
this.getTemperature = function() {
return this.temperature;
};
this.getHumidity = function() {
return this.humidity;
};
this.getPerssure = function() {
return this.perssure;
}
};
WeatherData.prototype = new Observable();
WeatherData.prototype.measurementsChange = function() {
this.changed = true;
var param = {
temperature: this.temperature,
humidity: this.humidity,
perssure: this.perssure
};
this.notifyObservers(param);
};
WeatherData.prototype.setMeasurements = function(temp, hum, pres) {
this.temperature = temp;
this.humidity = hum;
this.perssure = pres;
this.measurementsChange();
};
var CurrentConditionsDisplay = function(observable) {
this.temperature = 0;
this.humidity = 0;
this.perssure = 0;
Observer.call(this);
observable.addObserver(this);
this.display = function() {
console.log('Temperature:' + this.temperature + ', Humidity:' + this.humidity + ', Perssure:' + this.perssure);
};
};
CurrentConditionsDisplay.prototype.update = function(observable, args) {
this.temperature = observable.getTemperature();
this.humidity = observable.getHumidity();
this.perssure = observable.getPerssure();
this.display();
};
var weatherData = new WeatherData();
var display = new CurrentConditionsDisplay(weatherData);
weatherData.setMeasurements(1001, 2001, 3001);
weatherData.setMeasurements(1003, 2002, 3002);
weatherData.deleteObserver(display);
weatherData.setMeasurements(1001, 2001, 3001);
weatherData.setMeasurements(1003, 2002, 3002);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71