5. JavaScript 设计模式(观察者模式)

来源:互联网 发布:淘宝优质家具卖家 编辑:程序博客网 时间:2024/04/25 14:52

观察者模式是什么东东呢?我先用生活的例子,简单说明一下吧。 
① 报社的业务就是出版报纸 
② A、B、C三个人想某个报社订阅了报纸,只要他们有新的报纸出版,就会给这三个用户送报纸。只要他们三个一直是这个报社的订户,就会一直收到新的报纸。 
③ 当这三个人,其中一个不再想看报纸的时候,取消订阅,他们就不会收到报纸。 
④ 只要报社还在运营,就会一直有人向他们订阅报纸或取消报纸。

出版者 + 订阅者 = 观察者模式

观察者模式:定义一个对象之间的一对多依赖,这样一来,当一个对象改变状态时,他的所有依赖者都会收到通知并自动更新。

这里写图片描述

其实无论是我那个报社的例子,还是概念。都简单的说明了,观察者模式就是主体一变,对他的依赖就会收到改变的消息。

那代码怎么实现呢? 
以下例子不是本人所写,来自: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 参考这两个类封装一了个公共的接口。

  • Observable 类
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('子类实现的方法!');};
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4
  • 调用 
    这里我使用了 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;    }};// 跟 java 一样,被观察者需要继承 ObservableWeatherData.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;    // 跟 java 一样,被观察者需要继承 Observer    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) {    // 推模式 这里也是,和java的api一样有拉模式和推模式    //this.temperature = args.temperature;    //this.humidity = args.humidity;    //this.perssure = args.perssure;    // 拉模式    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
  • 运行结果 
    这里写图片描述

  • 要点(摘自 Head First) 
    ① 观察者模式定义了对象之间一对多的关系 
    ② 主题(也就是观察者)用一个共同的接口来更新观察者 
    ③ 观察者之间和被观察者之间用松耦合方式结合,被观察者不知道观察者的细节,只知道观察者实现了观察这的接口 
    ④ 使用此模式时,可从被观察者中推或者拉数据。 
    ⑤ 有多个观察者时,不可以依赖特定的通知顺序。


原创粉丝点击