观察者模式

 

 

Internet气象站项目:

  1、提供温度、气压、湿度的接口

  2、测量数据更新需要通知给第三方

  3、需要设计开放型API,便于其他的第三方公司也能接入气象站获取数据

 

 

public class CurrentConditions {
    
    private float mTemperature;
    private float mPressure;
    private float mHumidity;
    
    public void update(float mTemperature,float mPressure,float mHumidity)
    {
        this.mTemperature=mTemperature;
        this.mPressure=mPressure;
        this.mHumidity=mHumidity;
        display();
    }
    
    public void display()
    {
        System.out.println("***Today mTemperature: "+mTemperature+"***");
        System.out.println("***Today mPressure: "+mPressure+"***");
        System.out.println("***Today mHumidity: "+mHumidity+"***");
    }
}

 

public class WeatherData {

    private float mTemperatrue;
    private float mPressure;
    private float mHumidity;
    private CurrentConditions mCurrentConditions;

    public WeatherData(CurrentConditions mCurrentConditions) {
        this.mCurrentConditions = mCurrentConditions;
    }

    public float getTemperature() {
        return mTemperatrue;

    }

    public float getPressure() {
        return mPressure;

    }

    public float getHumidity() {
        return mHumidity;

    }

    public void dataChange() {
        mCurrentConditions.update(getTemperature(), getPressure(), getHumidity());
    }

    public void setData(float mTemperature, float mPressure, float mHumidity) {
        this.mTemperatrue = mTemperature;
        this.mPressure = mPressure;
        this.mHumidity = mHumidity;
        dataChange();
    }

}

 

public class InternetWeather {

    public static void main(String[] args) {
        CurrentConditions mCurrentConditions;
        WeatherData mWeatherData;
        
        mCurrentConditions=new CurrentConditions();
        mWeatherData=new         WeatherData(mCurrentConditions);
        
        mWeatherData.setData(30, 150, 40);
    }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2018-05-25 17:09  coderlzb  阅读(103)  评论(0编辑  收藏  举报