The observer pattern is a behavioral design pattern defining a one-to-many dependency. When a subject changes relevant state, it notifies registered observers so they can update. The subject uses an observer interface rather than hard-coding each concrete dependent, allowing subscriptions to vary.
The observer pattern has four main roles. The subject maintains subscriptions and offers attach, detach and notification operations. The observer interface specifies an update callback. A concrete subject owns the relevant state and triggers notification when that state changes. A concrete observer implements the callback and updates its dependent state.
In a pull-style arrangement, a concrete observer retains a reference to the concrete subject and reads its state when notified; in a push-style arrangement, notification carries the changed information. Either way, the subject's notification loop calls observers through their interface. The roles should specify how subscription changes during notification are handled, for example by iterating a snapshot of the current observer list.
A generic pull-style UML class diagram is shown below.
ConcreteSubject inherits subscription management from Subject; ConcreteObserver realizes the Observer interface. The subject can have many registered observers, while a concrete observer uses its subject reference to obtain state during update.Observer-pattern roles, subscriptions and pull-style state access
. Open triangles indicate inheritance or interface realization. Ordinary directed associations indicate references and do not assert ownership of observer lifetimes. Subject notification invokes the Observer update interface. Details.The classifications and typical uses are
| Pattern | Category | When to use it |
|---|---|---|
| Command pattern | Behavioral design pattern | Represent a request as an object, separating its invocation from the receiver. Commands can be queued or logged; undo additionally needs enough information to reverse the particular request. |
| Strategy pattern | Behavioral design pattern | Select among interchangeable algorithms through a common interface, such as different routing or scoring policies. |
| Adapter pattern | Structural design pattern | Wrap an existing component so clients can use it through a different required interface without changing that component. |
| State pattern | Behavioral design pattern | Delegate behavior to an object representing the current state, with transitions selecting another state object instead of scattering conditionals across operations. |
| Visitor pattern | Behavioral design pattern | Add operations across a relatively stable element-class hierarchy, commonly through double dispatch. Adding a new element type then usually requires updating the visitors. |
Articles by others on the same topic
There are currently no matching articles.
