Observer Pattern

(from Design Patterns)

Synopsis

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

Context

You want to maintain consistency between related objects, e.g. data and its visual representation, a filesystem and its cache, or a 3D sphere and the cube which is constrained to abut it.

Forces

Solution

Equip the subject with an interface for subscribing and unsubscribing to change notifications. Also include an interface for querying the subject, so that observers can get the information they need. Equip the observers with an interface for receiving the notifications from the subject.

When the subject is modified, it will notify its subscribers of a change, who will then have the opportunity to query the subject for details and update themselves.

Consequences

Implementation

For maximum speed, each subject can store references to its observers. However, this wastes space when a subject has no observers. For minimum space, you can use a global table of (subject, observer) pairs.

Before an observer can be deleted, it must unsubscribe from its subjects, to avoid dangling pointers. Garbage-collected languages are not exempt from this requirement.

Several variations are possible for reducing communication:

See Design Patterns or this page for sample code.

Known Uses

Languages based on constraints generally do not use the Observer pattern, because local propagation is inefficient for complex constraints and is susceptible to cycles. Instead, such languages use a centralized constraint solver.

Exercise

Suppose an observer initiates a modification to its subject, as is common with Documents and Views. The subject will then notify the observer of a change it already knows about. Can and should this spurious notification be avoided?


Thomas Minka
Last modified: Thu Jan 23 13:06:02 EST 1997