ES6设计模式之观察者模式

下面是观察者模式,其实是一对多的关系,向观察者发送数据。发送方式有两种,主动发送和被动发送。存在一个问题是主题可能把观察者不感兴趣的数据发送过去。方法简单实现也好实现。并且也容易理解。

class OriginData{ constructor(temperature,humidity,weather){ this.observerList = []; this.temperature = temperature; this.humidity = humidity; this.weather = weather; }

add(observer){ this.observerList.push(observer) }

remove(observer){ this.observerList.splice(this.observerList.findIndex(observer),1); }

// 这里有一个错误,数据改变,和通知观察者是两个动作,不能在一个函数里完成。

// dataChange(temperature,humidity,weather){

// for(let i=0;i<this.observerList.length;i++){

// this.observerList[i].update(temperature,humidity,weather);

// }

// }

notifyObserver(temperature,humidity,weather){ for(let i=0;i<this.observerList.length;i++){ this.observerList[i].update(temperature,humidity,weather); } }

dataChange(temperature,humidity,weather){ this.notifyObserver(temperature,humidity,weather); } }

class TemperaturePage{ constructor(temperature){ this.temperature = temperature; }

show(temperature){ console.log(the temperature is ${temperature}); }

update(temperature,humidity,weather){ if(this.temperature == temperature) return; this.temperature = temperature; this.show(temperature); } }

class HumidityPage{ constructor(humidity){ this.humidity = humidity; }

show(humidity){ console.log(the humidity is ${humidity}); }

update(temperature,humidity,weather){ if(this.humidity == humidity) return; this.humidity = humidity; this.show(humidity); } }

class WeatherPage{ constructor(weather){ this.weather = weather; }

show(temperature,humidity,weather){ console.log(the weather is ${weather}); }

update(weather){ if(this.weather == weather) return; this.weather = weather this.show(weather); } }

var objectWeather = new OriginData(“25d”,“moist”,“suny”); objectWeather.add(new TemperaturePage(“0d”)); objectWeather.dataChange(“22d”,“moist”,“suny”); objectWeather.dataChange(“22d”,“dry”,“suny”);

猜你喜欢

转载自www.cnblogs.com/node-jili/p/10161458.html