Observer model

0 is defined

The observer pattern defines one-to-many dependencies between objects so that when an object changes state, all of its dependencies are notified and updated automatically.

1 a brief introduction

Observer pattern can imagine a scenario, it is used to subscribe to the newspaper, the first thing you need to go to press to register their information, press newspaper delivery address according to the registered information table, a general idea of the observer pattern also is such, only nouns change, press into the theme, subscribers to observer, the observer pattern generally there are two types of implementation, Pull and push. As shown in Figure 1, a UML diagram of the Observer pattern,

2 instances

Java.util.Observable, java.util.Observer.Observable is a theme, and Observer is an Observer.

Let’s first mention a requirement. Now a weather company can obtain their respective data, such as temperature, humidity, wind direction, etc. We need to realize different types of bulletin boards according to their data, and when the data is updated, notice boards are needed to obtain data. For example, there is a bulletin board for temperature prediction, there is a bulletin board for current temperature description and so on, showing different forms. First of all, let’s forget about the observer model and imagine what else we can learn to implement? The policy pattern, for example, does encapsulate changes. When we use the bulletin board, we can add its implementation class, but it can’t tell the bulletin board to update the data. So it’s not possible. Don’t ask me any other patterns. I haven’t learned them yet. Subject to realize

import java.util.Observable;

public class WeatherData extends Observable {
    private float temperature;
    private float humidity;
    private float pressure;

    public WeatherData(a){}public void measurementsChanged(a){
        setChanged();
        notifyObservers();
    }
    
    // Use this method to customize the trigger weather station data update
    private void setMeasurements(float temperature,float humidity,float pressure){
        this.temperature=temperature;
        this.humidity=humidity;
        this.pressure=pressure;
        measurementsChanged();
    }
    // The following method opens the access method for the observer to pull
    public float getTemperature(a) {
        return temperature;
    }

    public float getHumidity(a) {
        return humidity;
    }

    public float getPressure(a) {
        returnpressure; }}Copy the code

Observer implementation

import java.util.Observable;
import java.util.Observer;

public class CurrentConditionsDisplay implements Observer {
    Observable observable;
    private float temperature;
    private float humidity;

    public CurrentConditionsDisplay(Observable observable) {
        this.observable = observable;
        observable.addObserver(this);
    }
    // The observer should implement the method
    @Override
    public void update(Observable o, Object arg) {
        if (o instanceof WeatherData){
            WeatherData weatherData= (WeatherData) o;
            this.temperature=weatherData.getTemperature();
            this.humidity=weatherData.getHumidity(); display(); }}public void display(a){
        System.out.println("current condition : "+temperature+"F degrees and"+ humidity+"% humidity"); }}Copy the code

Looking at the code above, let’s consider a few questions:

  1. How do I turn an object into an observer
  2. How is the topic notified, and how is it pulled or pushed
  3. How does the observer receive the notification

The answer:

  1. Let’s look at the observer construction public CurrentConditionsDisplay(Observable observable)In this case, we call the addObserver method to add the observer to the topic.
  2. First called in the main methodsetMeasurements, custom simulated weather station data update, in callmeasurementsChangedMethod to notify registered observers.
  3. This is whereObservableTwo ways, we know that the observer has two ways, one is pulling and one is pushing, corresponding to two of them. The first one isnotifyObservers(Object arg), using the way of pushing.

The second one is pullednotifyObservers() So we should see the similarities, is the topic notification method with data, above our sample code is to use the pull way, you can refer to.

3 Design Principles

  1. Interface oriented programming
  2. Use composition more than inheritance
  3. Packaging changes
  4. Strive for loose coupling design between interacting objects

4 points

  1. An observer defines a one-to-many relationship between objects
  2. Topics (observables) update observers with a common interface.
  3. The observer and the topic are loosely coupled, and the topic does not know the details of the observer, only that the observer implements the interface of the observer.
  4. With this mode, you can push and pull data from the observed (however, pushing is considered more correct).
  5. When there are multiple observers, you cannot rely on a particular order of notification.
  6. Java implements multiple observer pattern implementations. Including universaljava.util.Observable.
  7. Pay attention tojava.util.ObservableImplementation issues, (implementation-oriented issues)
  8. Implement it yourself if necessaryObservable

5 extension

  1. The downside of the Java Observer pattern – the downside of implementation-oriented programming.
  2. The benefit of setting setChange in Observer mode – increased program elasticity