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”);

转载于:https://www.cnblogs.com/node-jili/p/10161458.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值