Observer Design Pattern
The Observer design motif
The informal description: Excerpts from [Gamma et al. 1995] (adapted for
Intent: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
Structure: Original OMT diagram converted to UML (Why
- Knows its observers. Any number of Observer objects may observe a subject.
- Provides an interface for attaching and detaching Observer objects.
- Observer: defines an updating interface for objects that should be notified of changes in a subject.
- Stores state of interest to ConcreteObserver objects.
- Sends a notification to its observers when its state changes.
- Maintains a reference to a ConcreteSubject object.
- Stores state that should stay consistent with the subject's.
- Implements the Observer updating interface to keep its state consistent with the subject's.
- ConcreteSubject notifies its observers whenever a change occurs that could make its observers' state inconsistent with its own.
- After being informed of a change in the concrete subject, a ConcreteObserver object may query the subject for information. ConcreteObserver uses this information to reconcile its state with that of the subject.