Observer Pattern

In some cases, we need an one-to-many relationship between objects. If one object is modified, its dependent objects are to be notified automatically.

Intent

  • Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Implementation

Observer Pattern_第1张图片
Class Diagram of Observer Pattern
// Observable.java
public interface Observable {
    void registerObserver(Observer o);
    void removeObserver(Observer o);
    void notifyObservers();
}
// Observer.java
public interface Observer {
    void update(Data data);
}
// WeatherData.java
public class WeatherData implements Observable {

    public WeatherData() {
        observers = new LinkedList<>();
    }

    public void setData(Data data) {
        this.data = data;
        notifyObservers();
    }

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

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

    @Override
    public void notifyObservers() {
        for(Observer observer : observers) {
            observer.update(data);
        }
    }

    private List observers;
    private Data data;
}

Note: Java has built-in classes/interfaces to facilitate the Observer Pattern. Check out java.util.Observer and java.util.Observable for more information.

你可能感兴趣的:(Observer Pattern)