设计模式之观察者模式(Java)

问题引出

气象站项目
接到一个气象站的合同
可以监测到湿度温度这些变化
做一个开放接口 让第三方接入
现有接口:提供温度,气压和湿度的接口
目标:测量数据更新时需实时通知给第三方

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 注册 移除 通知

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值