javascript 观察者模式实现

观察者模式

定义了对象之间的一对多的依赖,这样一来,当一个对象改变状态时,它的所有依赖都会收到通知并更新。

var WeatherData = function(){ 
    var self = this;
    var observers = [];
    var _temperature = 0;
    var _humidity = 0;
    var _pressure = 0;

    this.registerObserver = function(o){
        observers.push(o);
    };

    this.removeObserver = function(o){
        var i = observers.indexOf(o);

        if(i >= 0){
            observers.splice(i, 1);
        }
    }

    this.notifyObserver = function(){
        for(var i = 0; i < observers.length; i++){
            var observer = observers[i];
            observer.update(_temperature, _humidity, _pressure);
        }
    }

    this.measurementsChanged = function(){
        self.notifyObserver();
    }

    this.setMeasurments = function(temperature, humidity, pressure){
        _temperature = temperature;
        _humidity = humidity;
        _pressure = pressure;
        self.measurementsChanged();
    }
}

var CurrentConditionsDisplay = function(WeatherData){

    var self = this;
    var _temperature;
    var _humidity;
    var _weatherData = WeatherData

     _weatherData.registerObserver(this);

    this.update = function(temperature, humidity, pressure){
        _temperature = temperature;
        _humidity = humidity;
        self.display();
    }

    this.display = function(){
        console.log('Current conditions: ' + _temperature + "F degrees and " + 
            _humidity + "% humidity");
    }
}

var weatherData = new WeatherData();
var currentDisplay = new CurrentConditionsDisplay(weatherData);

weatherData.setMeasurments(80, 65, 30.4);
weatherData.setMeasurments(82, 70, 29.2);
weatherData.setMeasurments(78, 90, 29.2);

result:

Current conditions: 80F degrees and 65% humidity
Current conditions: 82F degrees and 70% humidity
Current conditions: 78F degrees and 90% humidity

你可能感兴趣的:(node.js,JavaScript,node.js,观察者模式)