JAVA Design Patterns observer mode - Observer

When a funny thing happened, you can not miss it! There is a pattern that can help you object knows the current situation, do not miss the object of interest. Even objects at run time can decide whether to continue to be notified. With the viewer, you will be informed.

Introduction

Observer Pattern definition:

在对象之间定义一对多的依赖,这样一来,当一个对象改变状态,依赖它的对象都会收到通知,并自动更新。

Simple to understand

In order to facilitate understanding of observer mode, our newspaper as an example:

  1. The newspaper business is newspaper publishing;
  2. Subscribe to the newspaper to a newspaper, as long as they have a new newspaper publishing, it will be sent to you. As long as you are their subscribers, you will always receive a new newspaper.
  3. When you do not want to look at the newspaper when unsubscribe, they would not be sending a new newspaper.
  4. As long as the newspaper still operating, it would have been someone (or units)

If you subscribe to the newspaper to know how is going on, in fact, is an observer to know how it happens, but not the same name:
Publisher renamed the "theme" (Subject) or "observer" (Observable), Subscribers renamed the "observer" (observer).
Subject + = observer observer mode
theme is the definition of "a", the observer for the definition of "more", when the theme changes, it will inform the "Subscribe who "is the" observer "

scenes to be used

  • An abstract model has two aspects, one aspect of which is dependent on another aspect. These aspects will be encapsulated in a separate object manipulation thereof can be independently varied and reuse.
  • A change object will lead to other one or more objects is also changed, without knowing how many objects will be specifically changed, the degree of coupling between objects can be reduced.
  • An object must notify other objects, and do not know who these objects Yes.
  • You need to create a trigger in the system chain, will affect the behavior of the object A B object, the object will affect the behavior of B ...... C objects, you can trigger the creation of a chain mechanism uses the observer mode.

Example: There are a number of micro-channel public service, from time to time publish some news, public concern number can receive push messages, Unfollow not receive push messages.

Advantages and disadvantages

advantage

  1. Abstract observer and observed loosely coupled;
  2. Establish a trigger mechanism.

Shortcoming

  1. If there is a lot of direct and indirect objects observer observer, it will notify all observers have to spend a lot of time;
  2. If there is a circular dependency between the observer and the observed target, observe the target will trigger calls to circulate between them, may cause the system to crash.

Precautions

  1. JAVA class already has support for the observer pattern;
  2. Avoid circular references;
  3. If the order is executed, the system will cause a jam error observer, generally asynchronously.

achieve

Class Diagram

Implementation steps

Create an abstract theme - Subject

public interface Subject {

    //观察者订阅服务
    public void registerObserver(Observer o);

    //观察者取消订阅服务
    public void removeObserver(Observer o);

    //主题改变时,会被调用,通知所有观察者
    public void notifyObservers();
    
}

Create an abstract observer - Observer

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

Create a specific topic

public class WeatherData implements Subject {
    private ArrayList<Observer> observers;
    private float temperature;
    private float humidity;
    private float pressure;
    
    public WeatherData() {
        observers = new ArrayList<Observer>();
    }
    
    public void registerObserver(Observer o) {
        observers.add(o);
    }
    
    public void removeObserver(Observer o) {
        int i = observers.indexOf(o);
        if (i >= 0) {
            observers.remove(i);
        }
    }
    
    public void notifyObservers() {
        for (Observer observer : observers) {
            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();
    }

//  public float getTemperature() {
//      return temperature;
//  }
//  
//  public float getHumidity() {
//      return humidity;
//  }
//  
//  public float getPressure() {
//      return pressure;
//  }

}

Create a specific observer

public class CurrentConditionsDisplay implements Observer {
    private float temperature;
    private float humidity;
    private Subject weatherData;
    
    public CurrentConditionsDisplay(Subject weatherData) {
        this.weatherData = weatherData;
        //订阅
        weatherData.registerObserver(this);
    }
    
    public void update(float temperature, float humidity, float pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        display();
    }
    
    public void display() {
        System.out.println("Current conditions: " + temperature 
            + "F degrees and " + humidity + "% humidity");
    }
}

test

public class WeatherStation {

    public static void main(String[] args) {

        //创建主题
        WeatherData weatherData = new WeatherData();

        //创建观察者并订阅
        CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData);
//      StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData);
//      ForecastDisplay forecastDisplay = new ForecastDisplay(weatherData);

        //通知观察者
        weatherData.setMeasurements(80, 65, 30.4f);
//      weatherData.setMeasurements(82, 70, 29.2f);
//      weatherData.setMeasurements(78, 90, 29.2f);
    }
}

Epilogue

Design Patterns from life

Guess you like

Origin www.cnblogs.com/J-Simon/p/10926728.html