Observer Pattern

Also known as: Publisher/Subscriber, Dependents

The Observer pattern is useful for designing a communication model between a set of dependent objects (observers) and an object that they are dependent on (subject) allowing observers to synchronize their state with the subject. Any object with interest in the state of the subject needs to explicitly register/subscribe itself as an observer with the subject. Whenever the subject undergoes a change in its state, it notifies all of its registered observers so that they can synchronize. Subject-Observer relation is loose and can be 1-m or m-m.

Implementation

1- The subject should provide an interface for registering and unregistering observers.
2- The subject should provide an interface that enables observers to query the subject for state (pull model) OR the subject should send the state information that the observers may be interested in (push model)
3- Observers should provide an interface for receiving notifications from the subject.

Structure

observer.jpeg

Example

//Just for the sake of an example!
 
public interface Observer {
    public void update(Subject sub);
}
 
public class Subject {
    List<Observer> observers;
 
    public void registerObserver(Observer ob){
        observers.add(ob);
    }
 
    public void unRegisterObserver(Observer ob){
        observers.remove(ob);
    }
 
    public void notifyObservers(){
        for(Observer ob:observers){
            ob.update(this);
        }
    }
}

Related Patterns

  • When the dependency relationship between subjects and observers is particularly complex, an object that maintains these relationships might be required. We call such an object a ChangeManager. Its purpose is to minimize the work required to make observers reflect a change in their subject. It acts as mediator between subjects and observers and can be a Singleton to make it unique and globally accessible.
  • Callbacks are some form of observer pattern.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License