"Head First Design Patterns" study notes - observer mode

The second write mode observer, is the second chapter of the book, when it comes to this observer mode, the impression is quite profound, because last year the software designer soft test last question, is this observer test mode.

concept

Observer model defines dependencies between many objects, so that, when an object changes state, all of its dependents will be notified and updated automatically.

Example shows

Need to make a system that consists of three parts, weather stations (weather data acquisition of the actual physical device), the object of the WeatherData (tracking data from meteorological stations, and updates the bulletin boards) and the bulletin board (display the current weather conditions to the user to see) .

In this example, WeatherData physical object knows how to contact with weather stations, in order to obtain updated data. WeatherData object also update the display three billboards: the current situation (temperature, humidity, atmospheric pressure), weather statistics and weather forecasts.

Our goal is to build an application using the data acquired WeatherData object, and then update the three bulletin boards.

The method comprises the following WeatherData class.

getTemplate()
getHumidity()
getPressure()
measuermentsChanged()

We need to realize measurementChanged () method

  • When the new measurement data is ready, this method will be called
  • WeatherData when new measurement data, three billboards must be updated immediately
  • This system must be scalable, so that other developers to build custom bulletin board, users can add or remove any bulletin board, the three existing bulletin board, the current situation, weather statistics and weather forecast bulletin board.

Error Model

First, to demonstrate an error ah

public class WeatherData {
    /**
     * 目前状况布告板
     */
    CurrentConditionDisplay currentConditionDisplay;
    /**
     * 气象统计布告板
     */
    ForecastDisplay forecastDisplay;
    /**
     * 天气预报布告板
     */
    StatisticsDisplay statisticsDisplay;
    float temperature;
    float humidity;
    float pressure;

    public float getHumidity() {
        return humidity;
    }

    public float getPressure() {
        return pressure;
    }

    public float getTemperature() {
        return temperature;
    }

    public void measurementsChanged() {
        float temperature = getTemperature();
        float humidity = getHumidity();
        float pressure = getPressure();

        currentConditionDisplay.update(temperature, humidity, pressure);
        statisticsDisplay.update(temperature, humidity, pressure);
        forecastDisplay.update(temperature, humidity, pressure);
    }
}

The class which declares a few instance, and then update the bulletin board in measurementsChanged () method, the When the data has been updated, calls this method to update the bulletin board.

But the shortcomings of this approach large, it is programmed to achieve specific increase in the future when you remove or modify the program must bulletin board. So this is definitely not designed with too resource-intensive, and the need to repeatedly modify the code.

modify

Now we can talk to the topic, "the observer mode = + theme observer", then what is the subject, what is the observer?

Theme, is the object management data, equivalent to the monitoring center, when there is a change of data, the first time an object theme will inform the viewer object.

Observer object is registered to a topic, when there is a change of data, the data will be received subject of updates. It is similar to the relationship between newspapers and readers, when there is need for new news published, the newspaper printed newspaper, delivered into the hands of readers. This is one to many relationship, when an object is changed, other dependents are notified.

Design principles: In order to design loosely coupled interaction between objects and work.

For the observer objects, the viewer realizes only know the subject of an interface (Observer Interface), the subject does not need to know who the observer is a concrete class, done, or any other details. And the viewer can arbitrarily increase or decrease, but will not be affected. When there is a new observer, subject code without modification, you need to do is implement this observer interfaces in the new class, and then registered as an observer.

The observer pattern is to let the subject and observer loosely coupled, they can interact with each other but do not know the details. Change either between them both, will not affect the other, as the two are loosely coupled, so long as the interface between them is still observed, we are free to change them.

Then look at the specific bar code.

Code implementation example

First three interfaces, namely DisplayElement, Observer and Subject three interfaces, as the name implies, a first display interface for the bulletin board, the second interface is a viewer interface to update data, the third interface is a theme interface for registering observers.

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 observer);
}

Next we mentioned before, WeatherData class, due to the need to inform the observer data updates, so it is a theme, you need to implement Subject interface contains a collection of observer.

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

    public WeatherData() {
        observers = new ArrayList();
    }

    @Override
    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    public void removeObserver(Observer observer) {
        int i = observers.indexOf(observer);
        if (i >= 0) {
            observers.remove(observer);
        }
    }

    public void notifyObservers() {
        for (int i = 0; i < observers.size(); i++) {
            Observer observer = (Observer) observers.get(i);
            observer.update(temperature, humidity, pressure);
        }
    }

    public void measurementsChanged() {
        notifyObservers();
    }

    public void setMeasurements(float temperature, float humidity, float pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementsChanged();
    }
}

is a collection of the observer observers, while simultaneously constructing Weather object instantiates an empty set, used to make the observer register a container object, the remaining three properties are required attributes signboard.

registerObserver (Observer observer) method is a method to register an observer, empathy removeObserver (Observer observer) is to remove the observer method.

the notifyObservers () method is to notify the viewer through the collection of data updates, measurementsChanged () is to update the data in the previously mentioned methods.

setMeasurements (float temperature, float humidity, float pressure) (float temperature, float humidity, float pressure) is to set the three attributes of method, while calling measurementsChanged () method updates the data announcement board.

Then there is the bulletin board CurrentConditionsDisplay class. It implements the observer interface and an implementation interface contains a theme object, initialized instance when objects need to pass the theme registration, two interface methods to achieve.

public class CurrentConditionsDisplay implements Observer, DisplayElement {
    private float temperature;
    private float humidity;
    private Subject weatherData;

    public CurrentConditionsDisplay(Subject weatherData) {
        this.weatherData = weatherData;
        weatherData.registerObserver(this);
    }

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

    @Override
    public void update(float temp, float humidity, float pressure) {
        this.temperature = temp;
        this.humidity = humidity;
        display();
    }
}

Finally, the test class.

public class WeatherStation {
    public static void main(String[] args) {
        WeatherData weatherData = new WeatherData();

        CurrentConditionsDisplay currentConditionsDisplay = new CurrentConditionsDisplay(weatherData);
        weatherData.setMeasurements(80,65, 30.4f);
    }
}

Creating a theme object, creating a bulletin board object is updated by the data subject objects, prints out the data bulletin board to show the console.

This is a clear-to-many configuration, there is a set of one, there one of a plurality of objects. When data needs to be updated, call the method of a series of actions, which will be after two loosely coupled, you want to add a new bulletin board only need to create a new class that implements the Observer interface, then the object can be registered to the theme.

The next design patterns continue tomorrow.

Published 26 original articles · won praise 2 · Views 2331

Guess you like

Origin blog.csdn.net/qq_42909545/article/details/104781334