Observer mode

In many scenarios, it is necessary to establish a one-to-many, timely and weakly coupled message, design mode is interface-oriented, and the observer mode is introduced.

 

Scene: Meteorological data is sent to three information editions: current data, meteorological statistics, and weather forecast. Once the meteorological data is updated, the three information editions need to display the message panel information.

See the code for not using observer mode:

/**
 * Update 3 information editions, current data, weather statistics, and weather forecast using weather data
 */
public class weather {
    private float temperature;//temperature
    private float humidity;//humidity
    private float pressure;//pressure

    public float getTemperature() {
        return temperature;
    }

    public weather(float temperature, float humidity, float pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
    }

    public void setTemperature(float temperature) {
        this.temperature = temperature;
    }

    public float getHumidity() {
        return humidity;
    }

    public void setHumidity(float humidity) {
        this.humidity = humidity;
    }

    public float getPressure() {
        return pressure;
    }

    public void setPressure(float pressure) {
        this.pressure = pressure;
    }
    public void paramChanged(){
        float temp = getTemperature();
        float hum = getHumidity();
        float pressure = getPressure();
        currentCondutionDisplay.update(temp,hum,pressure); //If you want to add a delete infoboard, you need to weather Class deletion adds, resulting in strong coupling


    }
}
class currentCondutionDisplay {
    private float temperature;//temperature
    private float humidity;//humidity
    private float pressure;//pressure

    public currentCondutionDisplay(float temperature, float humidity, float pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
    }
    protected static void update(float temperature, float humidity, float pressure){

        display(temperature,humidity,pressure);

    }


    private static void display(float temperature, float humidity, float pressure){
        System.out.println("Current weather temperature  "+temperature + "humidity"+humidity+"pressure "+pressure);
    }
}
public class testmain {
    public static void main(String[] args) {
        weather weatherdata = new weather(38,60,1000);
        weatherdata.paramChanged();

    }
}

Disadvantages: Assuming you need to add and delete information versions, you need to modify the weather class to create strong coupling between classes.

For this, introduce the observer mode in design mode

Observer mode

Observer Pattern means that when there is a one-to-many relationship between objects, the Observer Pattern is used. For example, when an object is modified, the object that depends on it is automatically notified. The observer mode is behavioral.

Observer Mode Purpose: Solve the strong coupling problem.

Say dry, define dull, for example: Post Office Send Example

Xiao Ming (that is, you) sends letters to the post office. The post office can be regarded as the subject of the observer. Xiao Ming wants to send letters to three people through the post office, namely, girlfriend Xiao Hong, Xiao Ming's parents and Xiao Ming's friend Xiao Zhang. These three people can be defined as observers. We will write three recipients into a list of receipts, that is, the list of observers. Register with the post office. Once the post office receives the letter, it updates its status and notifies three recipients, the observers. When the recipients (the observers) receive the letter, they update their status and act differently. Xiao Hong sends a letter with a rose petal to Xiao Ming, and Xiao Ming's parents send her native products to Xiao Ming. Xiao Zhang is calling Xiao Ming directly when he receives the letter. But there are also unexpected situations, such as Xiao Hong getting angry and refusing to accept Xiao Hong's letters, so the post office will temporarily remove Xiao Hong from the recipient list. Then, if Xiao Ming wants to write a letter to Xiao Hong's friend Xiao Zi to let her talk to Xiao Hong, add Xiao Zi to the recipient list.

The observer mode is similar, except that the recipient is defined as the observer, the observer interface is implemented, the post office is defined as the observer, the principal interface is implemented, the post office and the observer form a one-to-many relationship, the post office can delete the added observer, and push the update status to the observer.

In this case, the weather class is the main body of the meteorological data, which implements the subject interface. It has three information versions as observers, three information versions as observers, and the update of the meteorological data as update's own status. The observer and the main body have a registered relationship to establish a connection. The specific implementation can observe the following flowchart

 

 

As shown in the figure, the three panels implement the displayinterface in addition to the obsever interface, with the update() and display() methods of the interface, but the three information versions can override both methods.

Code implementation:

public interface DisplayElement {
    public void display();
}

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

public interface Subject {
    public void registerObserver(Observer o);
    public void removeObserver(Observer o);
    public void notifyObservers();
}
public class currentConditionsDisplay implements Observer, DisplayElement {
    //Implemented observer Interface, available from weather Get Changed
    private float temperature;
    private float humidity;
    private Subject weather;

    public currentConditionsDisplay(Subject weather) {//Register, contact subject
        this.weather = weather;
        weather.registerObserver(this);
    }

    @Override
    public void display() {
        System.out.println("Current conditions: "+ temperature +" degrees and "+ humidity+ " %humidity");

    }

    @Override
    public void update(float temp, float humidity, float pressure) {
        this.temperature = temp;
        this.humidity = humidity;//Save temperature and humidity, call display
        display();


    }
}
public class forecastDisplay implements Observer, DisplayElement {
    //Implemented observer Interface, available from weather Get Changed
    private float temperature;
    private float humidity;
    private Subject weatherData;
    private  String status;
    public forecastDisplay(Subject weatherData) {//Register, contact subject
        this.weatherData = weatherData;
        weatherData.registerObserver(this);
    }

    @Override
    public void display() {


        if (this.temperature>37){
            this.status = "too hot";
        }
        if(this.temperature<38 & this.temperature>20 & this.humidity>45){
            this.status = "warm";
        }if(this.temperature<=10){
            this.status = "too cold";
        }

        System.out.println("today weather: "+ this.status);

    }

    @Override
    public void update(float temp, float humidity, float pressure) {
        this.temperature = temp;
        this.humidity = humidity;//Save temperature and humidity, call display
        display();


    }
}

Test code:

public class weatherStation {
    public static void main(String[] args) {
        weather weather = new weather();
        currentConditionsDisplay currentConditionsDisplay = new currentConditionsDisplay(weather);
        forecastDisplay forecast = new forecastDisplay(weather);
        weather.setParams(10,20,1000);
        weather.setParams(25,60,1000);
        weather.setParams(39,60,1000);
    }
}

Achieving results:

 

 

Advantages and disadvantages of the observer model:

Advantages: 1. The observer and the observer are abstractly coupled. 2. Set up a trigger mechanism.

Disadvantages: 1. It takes a lot of time to notify all the observers if there are many direct and indirect observers for an observee. 2. If there is a circular dependency between the observer and the observer target, the observer target triggers a circular call between them, which may cause the system to crash. 3. There is no mechanism for observer mode to let the observer know how the observed object has changed, only that the observed object has changed.

Code: https://github.com/akadiaego/designPatterns

Added by dan1956 on Thu, 03 Feb 2022 19:11:03 +0200