Observer Pattern



  • 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

    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.


登录后回复
 

与 BitTiger Community 的连接断开,我们正在尝试重连,请耐心等待