Pattern: Observer

Synopsis

The Observer pattern is used to create an association among classes that have a need to be aware of the bevavior of one class. The pattern provides a way to inform all of the related classes when one of them is updated.

Context

This pattern can be used when one has several interdependent objects, and changes occurring in one object necessitate updating the dependent objects as well. It is generally used when the quantity of related objects is not known from the start, since it provides an easy means for adding related objects dynamically.

Forces

There may be a situation in which a piece of data is stored in one location, but several different objects are referencing the value of that data. If the data changes, the objects referring to it need to be made aware of the change; otherwise they would be referring to an incorrect and/or outdated value.

Solution

We create any number of classes that implement the Observer interface. This interface defines an Update() method. The Subject itself (the class being observed) defines Attach(observer), Remove(observer), and Notify() methods.

The general pattern for the Observer pattern is as follows.

Consequences

Implementation

Getting a message from a Subject to all Observers can happen in two ways. One way is to have the Observers continuously poll the Subject to check if any changes have occurred. The alternative approach, and the one embodied by the Observer pattern, is to have the Subject push the updates to all Observer objects.

When the Subject's data changes, it calls its Notify method which then iterates through all of the attached observers and calls their respective Update methods.

Related Patterns

Mediator

Sources

Pattern Digest
c2.com


Modified: 11-Feb-2004
E.J. Yerzak