The 23 GoF design patterns and Dependency Injection – choose a pattern Abstract Factory design patternBuilder design patternFactory Method design patternPrototype design patternSingleton design patternAdapter design patternBridge design patternComposite design patternDecorator design patternFacade design patternFlyweight design patternProxy design patternChain of Responsibility design patternCommand design patternInterpreter design patternIterator design patternMediator design patternMemento design patternObserver design patternState design patternStrategy design patternTemplate Method design patternVisitor design patternDependency Injection design pattern

Observer Design Pattern

Behavioral pattern. Behavioral design patterns are concerned with algorithms and the assignment of responsibilities between objects.

Intent: "Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically." [GoF]

Open in the interactive referenceDownload the PDF reference

Intent

The intent of the Observer design pattern is to:
"Define a one-to-many dependency between objects so that when one object
changes state, all its dependents are notified and updated automatically."
[GoF]
See Problem and Solution sections for a more structured description of the intent.

  • The Observer design pattern solves problems like:
    • How can a one-to-many dependency between objects be defined
      without making the objects tightly coupled?
    • How can an object notify an open-ended-number of other objects?
  • Coupling is the degree to which objects depend on each other.
    • Tightly coupled objects are hard to implement, change, test, and reuse
      because they depend on (refer to and know about) many different objects (having different interfaces).
    • Loosely coupled objects are easier to implement, change, test, and reuse
      because they have only minimal dependencies on other objects.
  • The Observer pattern describes how to solve such problems:
    • Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
    • The key idea in this pattern is to establish a flexible notification-registration mechanism that notifies all registered objects automatically when an event of interest occurs.

Problem

The Observer design pattern solves problems like:
How can a one-to-many dependency between objects be defined
without making the objects tightly coupled?
How can an object notify an open-ended number of other objects?
See Applicability section for all problems Observer can solve. See Solution section for how Observer solves the problems.

  • An inflexible way to define a one-to-many dependency between objects is to define one object (Subject1) that implements updating the state of dependent objects (Dependent1,Dependent2,…). That means, subject must know how to update the state of many different objects (having different interfaces).
  • This commits (tightly couples) the subject to particular dependent objects and makes it impossible to change the objects (add new ones or remove existing ones) indepen­dently from (without having to change) the subject. It stops the subject from being reusable and makes the subject hard to test.
    Tightly coupled objects are hard to implement, change, test, and reuse
    because they depend on (refer to and know about) many different objects.

    "You don't want to achieve consistency by making the classes tightly coupled, because that reduces their reusability." [GoF, p293]
  • That's the kind of approach to avoid if we want to keep the objects in a one-to-many dependency loosely coupled.
  • For example, a data object and multiple presentation objects in a GUI/Web application.
    When the data object changes state, all presentation objects that depend on this data object's state should be updated (synchronized) automatically and immediately to reflect the data change (see Sample Code / Example 2).
  • For example, event handing in a GUI/Web application.
    When a user clicks a button, all objects that depend on (listen for) the button's 'click event' should be notified that a 'click event' occurred (see Sample Code / Example 3/4).

Solution

The Observer design pattern provides a solution:
Define Subject and Observer objects
so that when a subject changes state,
all registered observers are notified and updated automatically.

Describing the Observer design in more detail is the theme of the following sections.
See Applicability section for all problems Observer can solve.

  • The key idea in this pattern is to establish a flexible notification-registration interaction by notifying (calling update on) all registered observers automatically when an event of interest occurs.
  • Define Subject and Observer objects:
    • Subject defines an interface for registering and unregistering observers (attach(o), detach(o)) and for notifying observers (notify()), i.e., calling update() on all registered observers.
    • Observer defines an interface for updating state (update()), i.e., synchronizing observer's state with subject's state.
  • When a subject changes state, all registered observers are notified and updated automatically (for each o in observers: o.update()).
  • This enables loose coupling between subject and observers.
    Subject and observers have no explicit knowledge of each other. An open-ended number of observers can observe a subject. New observers can be added to and existing ones can be removed from the subject independently and dynamically.
  • "This kind of interaction is also known as publish-subscribe.
    The subject is the publisher of notifications. It sends out these notifications without having to know who its observers are. Any number of observers can subscribe to receive notifications." [GoF, p294]

Motivation

Consider the left design (problem):

  • Tight coupling
    between subject and dependents.
    • Subject implements (is responsible for) updating dependent objects.
    • Subject refers to and knows about (how to update) many different objects having different interfaces (tight coupling).
    • Adding new depen­dent objects  or re­moving existing ones requires changing subject.
    • Tightly coupled objects depend on (refer to and know about) many other objects having different interfaces, which makes the objects hard to implement, change, test, and reuse.

Consider the right design (solution):

  • Loose coupling
    between subject and observers.
    • Subject delegates (the responsibility for) updating to dependent objects (observers).
    • Subject only refers to and knows about the common Observer interface for updating state (loose coupling).
    • An open-ended number of observers can be added/removed independently and dynamically (attach(o)/detach(o)).
    • Loosely coupled objects have only minimal dependencies (by working through a com­mon interface), which makes the objects easier to to implement, change, test, and reuse.

Applicability

Design Problems

  • Defining One-to-many Dependencies Between Objects
    • How can a one-to-many dependency between objects be defined
      without making the objects tightly coupled?
    • How can be ensured that when one object changes state
      an open-ended number of dependent objects are updated automatically?
    • How can consistency between dependent objects be maintained?
  • Flexible Notification-Registration (Publish-Subscribe) Interaction
    • How can an object notify an open-ended number of other objects?
    • How can a publisher notify an open-ended number of subscribers?

Structure

Static Class Structure

  • Subject
    • Refers to the Observer interface to update dependent objects (observers) and is independent of how the objects are updated.
    • Maintains a list of dependent objects (observers).
    • Defines an interface for registering and unregistering observers (attach(o), detach(o)).
    • Defines an interface for notifying observers (notify()), i.e., calling update() on all registered observers: for each o in observers: o.update().
    • Usually, calls notify() on itself when its state changes.
  • Subject1
    • Stores state observers depend on.
  • Observer
    • Defines an interface for updating state (update()), i.e., synchronizing observer's state with subject's state.
  • Observer1,Observer2,,…
    • Dependent objects that implement the Observer interface.
    • Store state that should stay consistent with subject's state.
    • Maintain a reference (subject) to the subject they observe to get the changed data (getState).

Dynamic Object Collaboration

  • In this sample scenario, Observer1 and Observer2 objects register themselves on a Subject1 object and are subsequently notified and updated when Subject1 changes state.
  • The interaction starts with the Observer1 and Observer2 objects that call attach(this) on Subject1 to register themselves.
  • Thereafter, let's assume that the state of Subject1 changes, Subject1 calls notify() on itself.
  • notify() calls update() on the registered Observer1 and Observer2 objects, which in turn get the changed data (getState()) from Subject1 to update (synchronize) their state.
  • There are different ways to exchange (push/pull) data between Subject and Observer objects (see Implementation).
  • See also Sample Code / Example 1.

Consequences

Advantages (+)

  • Decouples subject from observers.
    • Subject only refers to and knows about the simple Observer interface for updating (synchronizing) state (update()).
    • "Because Subject and Observer aren't tightly coupled, they can belong to different layers of abstraction in a system. [GoF, p296]
    • Loosely coupled objects are easier to implement, change, test, and reuse.
  • Makes adding/withdrawing observers easy.
    • Observers can be added to (attach(o)) and withdrawn from a subject independently and dynamically.
    • Usually, observers are responsible for registering and unregistering themselves on a subject.
    • Subject's sole responsibility is to hold a list of observers and notify (call update() on) them when its state changes.

Disadvantages (–)

  • Can make the update behavior complex.
    • A change on the subject may cause a cascade of updates to observers and their dependent objects.
    • The Mediator design pattern can be applied to implement a complex dependency relationship between subject(s) and observers.

Implementation

Implementation Issues

  • Implementation Variants
    • The Subject and Observer interfaces must be designed carefully so that the data can be passed/accessed efficiently to let observers know what changed in subject. There are two main variants:
  • Variant1: Push Data
    • Subject passes the changed data to its observers:
      update(data1,data2,…)
    • The Observer interface may get complex because it must enable to pass in the changed data for all supported observers (whether the data is simple or complex).
  • Variant2: Pull Data
    • Subject passes nothing but itself to its observers so that they can call back to get (pull) the required data from subject:
      update(this)
    • The Subject interface may get complex because it must enable all supported observers to access the needed data.
  • "The pull model emphasizes the subject's ignorance of its observers, whereas the push model assumes subjects know something about their observers' needs." [GoF, p298]

Sample Code 1

Basic Java code for implementing the sample UML diagrams.

 1  package com.sample.observer.basic;
 2  public class MyApp { 
 3      public static void main(String[] args) { 
 4          Subject1 s1 = new Subject1();
 5          // Creating observers and registering them on subject1.
 6          Observer o1 = new Observer1(s1);
 7          Observer o2 = new Observer2(s1);
 8            
 9          System.out.println("Changing state of Subject1 ...");
10          s1.setState(100);
11      } 
12  } 
Changing state of Subject1 ...
Subject1 : State changed to : 100
           Notifying observers ...
Observer1: State updated to : 100
Observer2: State updated to : 100

 1  package com.sample.observer.basic;
 2  import java.util.ArrayList;
 3  import java.util.List;
 4  public abstract class Subject { 
 5      private List<Observer> observers = new ArrayList<Observer>();
 6      // Registration interface.
 7      public void attach(Observer o) { 
 8          observers.add(o);
 9      } 
10      // Notification interface.
11      // notify() is already used by the Java Language (to wake up threads).
12      public void notifyObservers() { 
13          for (Observer o : observers)
14              o.update();
15      } 
16  } 

 1  package com.sample.observer.basic;
 2  public class Subject1 extends Subject { 
 3      private int state = 0;
 4      //
 5      public int getState() { 
 6          return state;
 7      } 
 8      void setState(int state) { 
 9          this.state = state;
10          System.out.println(
11              "Subject1 : State changed to : " + state + 
12              "\n           Notifying observers ...");
13          // Notifying observers that state has changed.
14          notifyObservers();
15      } 
16  } 

 1  package com.sample.observer.basic;
 2  public abstract class Observer { 
 3      // Synchronizing observer's state with subject's state.
 4      public abstract void update();
 5  } 

 1  package com.sample.observer.basic;
 2  public class Observer1 extends Observer { 
 3      private int state;
 4      private Subject1 subject;
 5      public Observer1(Subject1 subject) { 
 6          this.subject = subject;
 7          // Registering this observer on subject.
 8          subject.attach(this); 
 9      } 
10      public void update() { 
11          this.state = subject.getState();
12          System.out.println(
13              "Observer1: State updated to : " + this.state);
14      } 
15  } 

 1  package com.sample.observer.basic;
 2  public class Observer2 extends Observer { 
 3      private int state;
 4      private Subject1 subject;
 5      public Observer2(Subject1 subject) { 
 6          this.subject = subject;
 7          // Registering this observer on subject.
 8          subject.attach(this); 
 9      } 
10      public void update() { 
11          this.state = subject.getState();
12          System.out.println(
13              "Observer2: State updated to : " + this.state);
14      } 
15  }