Interpretation of Observer Pattern

Table of contents

problem introduction

Weather Forecast Project Requirements

Weather Forecast Design Scheme 1-Common Scheme

Traditional code implementation

 Observer pattern principle

Observer mode solves weather forecast needs

 Code

  Benefits of the Observer Pattern


problem introduction

Weather Forecast Project Requirements

1) The weather station can publish the temperature, humidity, air pressure, etc. measured every day in the form of announcements (for example, to its own website or a third party).
2) An open API needs to be designed so that other third parties can also access the weather station to obtain data.
3) Provide interfaces for temperature, air pressure and humidity
4) When the measurement data is updated, it must be able to notify the third party in real time

Weather Forecast Design Scheme 1-Common Scheme

 1) Through the getXxx method. Can allow third parties to intervene and obtain relevant information

2) When the data is updated, the weather station updates the data by calling dataChange(). When the data is updated, the minimum message can be obtained, of course, it can also be sent by push.

 CurrentConditions can be understood as our Meteorological Bureau website

Traditional code implementation

CurrentConditions 

public class CurrentConditions {
    // 温度,气压,湿度
    private float temperature;
    private float pressure;
    private float humidity;
    //更新 天气情况,是由 WeatherData 来调用,我使用推送模式
    public void update(float temperature, float pressure, float humidity) {
        this.temperature = temperature;
        this.pressure = pressure;
        this.humidity = humidity;
        display();
    }
    //显示
    public void display() {
        System.out.println("***Today mTemperature: " + temperature + "***");
        System.out.println("***Today mPressure: " + pressure + "***");
        System.out.println("***Today mHumidity: " + humidity + "***");
    }

}

 WeatherData 

public class WeatherData {
    private float temperatrue;
    private float pressure;
    private float humidity;
    private CurrentConditions currentConditions;
    //加入新的第三方
    public WeatherData(CurrentConditions currentConditions) {
        this.currentConditions = currentConditions;
    }
    public float getTemperature() {
        return temperatrue;
    }
    public float getPressure() {
        return pressure;
    }
    public float getHumidity() {
        return humidity;
    }
    public void dataChange() {
    //调用 接入方的 update
        currentConditions.update(getTemperature(), getPressure(), getHumidity());
    }
    //当数据有更新时,就调用 setData
    public void setData(float temperature, float pressure, float humidity) {
        this.temperatrue = temperature;
        this.pressure = pressure;
        this.humidity = humidity;
    //调用 dataChange, 将最新的信息 推送给 接入方 currentConditions
        dataChange();
    }
}

 Client 

public class Client {
    public static void main(String[] args) {
        //创建接入方 currentConditions
        CurrentConditions currentConditions = new CurrentConditions();
        //创建 WeatherData 并将 接入方 currentConditions 传递到 WeatherData 中
        WeatherData weatherData = new WeatherData(currentConditions);
        //更新天气情况
        weatherData.setData(30, 150, 40);
        //天气情况变化
        System.out.println("============天气情况变化=============");
        weatherData.setData(40, 160, 20);
    }
}

Problem Analysis
1) The problem of other third parties accessing the weather station to obtain data

2) Unable to dynamically add a third party (Sina website) at runtime
3) Violation of ocp principle => Observer mode
//In WeatherData, when adding a third party, it is necessary to create a corresponding third party bulletin board object, And add it to dataChange, which is not conducive to maintenance, nor is it dynamically added
public void dataChange() { currentConditions.update(getTemperature(), getPressure(), getHumidity()); }

 Observer pattern principle

1) Observer mode is similar to ordering milk business
2) Milk station/weather bureau: Subject
3) User/third-party website: Observer
 Subject: registration, removal and notification
1) registerObserver registration
2) removeObserver removal
3) notifyObservers( ) Notify all registered users. According to different needs, it can be to update data for users to fetch, or to implement push, depending on specific needs.
 Observer: receive input

Observer mode: A design scheme of many-to-one dependence between objects. The dependent object is the Subject, and the dependent object is the Observer. The Subject notifies the Observer of changes. When the user is Observer, it is the party with more.

Observer mode solves weather forecast needs

 Code

Observer 

public interface Observer {
    public void update(float temperature, float pressure, float humidity);
}

 Subject 

public interface Subject {
    public void registerObserver(Observer o);
    public void removeObserver(Observer o);
    public void notifyObservers();
}

 CurrentConditions 

public class CurrentConditions implements Observer{
    // 温度,气压,湿度
    private float temperature;
    private float pressure;
    private float humidity;
    @Override
    public void update(float temperature, float pressure, float humidity) {
        this.temperature=temperature;
        this.pressure=pressure;
        this.humidity=humidity;
        display();
    }
    public void display(){
        System.out.println("***Today mTemperature: " + temperature + "***");
        System.out.println("***Today mPressure: " + pressure + "***");
        System.out.println("***Today mHumidity: " + humidity + "***");
    }
}

BaiduSite  

public class BaiduSite implements Observer{
    // 温度,气压,湿度
    private float temperature;
    private float pressure;
    private float humidity;
    @Override
    public void update(float temperature, float pressure, float humidity) {
        this.temperature=temperature;
        this.pressure=pressure;
        this.humidity=humidity;
        display();
    }
    public void display(){
        System.out.println("***Today mTemperature: " + temperature + "***");
        System.out.println("***Today mPressure: " + pressure + "***");
        System.out.println("***Today mHumidity: " + humidity + "***");
    }
}

 WeatherData  

public class WeatherData  implements  Subject{
    private float temperature;
    private float pressure;
    private float humidity;
    private ArrayList<Observer> observers;

    public WeatherData() {
        observers = new ArrayList<Observer>();
    }
    public float getTemperature() {
        return temperature;
    }
    public float getPressure() {
        return pressure;
    }
    public float getHumidity() {
        return humidity;
    }

    public void  setData(float temperature,float pressure,float humidity){
        this.temperature = temperature;
        this.pressure = pressure;
        this.humidity = humidity;
    //调用 dataChange, 将最新的信息 推送给 接入方 currentConditions
        notifyObservers();
    }

    //添加一个观察者
    @Override
    public void registerObserver(Observer o) {
        observers.add(o);
    }

    //移除一个观察者
    @Override
    public void removeObserver(Observer o) {
        if(observers.contains(o)) {
            observers.remove(o);
        }
    }

    @Override
    public void notifyObservers() {
        // TODO Auto-generated method stub
        for(int i = 0; i < observers.size(); i++) {
            observers.get(i).update(this.temperature, this.pressure, this.humidity);
        }
    }
}

client  

public class client {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //创建一个 WeatherData
        WeatherData weatherData = new WeatherData();
        //创建观察者
        CurrentConditions currentConditions = new CurrentConditions();
        BaiduSite baiduSite = new BaiduSite();
        //注册到 weatherData
        weatherData.registerObserver(currentConditions);
        weatherData.registerObserver(baiduSite);
        //测试
        System.out.println("通知各个注册的观察者, 看看信息");
        weatherData.setData(10f, 100f, 30.3f);
        weatherData.removeObserver(currentConditions);
        //测试
        System.out.println();
        System.out.println("通知各个注册的观察者, 看看信息");
        weatherData.setData(10f, 120f, 30.3f);

    }
}

  Benefits of the Observer Pattern

1) After the observer mode is designed, users (Observer) will be managed in a collective way, including registration, removal and notification.
2) In this way, if we add observers (this can be understood as a new bulletin board), there is no need to modify the core class WeatherData, and the code will not be modified, which complies with the ocp principle

Guess you like

Origin blog.csdn.net/m0_62436868/article/details/130296976