问题引出
气象站项目
接到一个气象站的合同
可以监测到湿度温度这些变化
做一个开放接口 让第三方接入
现有接口:提供温度,气压和湿度的接口
目标:测量数据更新时需实时通知给第三方
WeatherData类
先写代码不使用观察者模式
package com.weatherstation.mark;
public class WeatherTest {
public static void main(String[] args) {
CurrentWeatherBoard currentWeatherBoard;
WeatherStation weatherStation;
currentWeatherBoard=new CurrentWeatherBoard();
weatherStation=new WeatherStation(currentWeatherBoard);
weatherStation.setData(28,160,30);
}
}
package com.weatherstation.mark;
public class CurrentWeatherBoard {
private float currentTemperature;
private float currentPressure;
private float currentHumidity;
public void update(float currentTemperature,float currentPressure,float currentHumidity){
this.currentTemperature=currentTemperature;
this.currentPressure=currentPressure;
this.currentHumidity=currentHumidity;
display();
}
public void display(){
System.out.println("Now currentTemperature:"+currentTemperature);
System.out.println("Now currentPressure:"+currentPressure);
System.out.println("Now currentHumidity:"+currentHumidity);
}
}
package com.weatherstation.mark;
public class WeatherStation {
private float currentTemperature;
private float currentPressure;
private float currentHumidity;
private CurrentWeatherBoard currentWeather;
public float getCurrentTemperature() {
return currentTemperature;
}
public float getCurrentPressure() {
return currentPressure;
}
public float getCurrentHumidity() {
return currentHumidity;
}
public WeatherStation(CurrentWeatherBoard currentWeather){
this.currentWeather=currentWeather;
}
public void update(float tempTemperature,float tempPressure,float tempHumidity){
this.currentTemperature=currentTemperature;
this.currentPressure=currentPressure;
this.currentHumidity=currentHumidity;
}
//增加公告板 code需要改变
public void dataChange(){
currentWeather.update(getCurrentTemperature(),getCurrentPressure(),getCurrentHumidity());
}
public void setData(float tempTemperature,float tempPressure,float tempHumidity){
this.currentTemperature=tempTemperature;
this.currentPressure=tempPressure;
this.currentHumidity=tempHumidity;
dataChange();
}
}
问题如果新加公告栏 需要改变代码 扩展性不好
怎么解决 思考问题
观察者模式原理
订报业务
1.报社 Subject
2.用户 Observer
2.Subject 注册 移除 通知