美文网首页程序员
Observer Pattern

Observer Pattern

作者: Hackjutsu | 来源:发表于2016-04-15 04:30 被阅读42次

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

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<Observer> 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

    本文链接:https://www.haomeiwen.com/subject/lofnlttx.html