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)
Example
An object is created to represent the current session of a logged-in user at a webservice. Other parts of the system need to know when the session ends, whether that is because the user has logged out, the session has timed out, the connection has failed, or any other reason. It’s also important to note the length of time the session was active at the moment it expires.
The Observer would allow any part of the system that was “interested” to sign up for the notification.
-AMAZONPOLLY-ONLYWORDS-START-
Diagram
-AMAZONPOLLY-ONLYWORDS-END-
Qualities and principles
The observed object is decoupled from the observers; both their nature and number. Each observer has a single reason to sign up for notification. The design is open-closed to new observers.
Testing
A test can use a Mock Observer to record what happens when the event in question is triggered. Each observer can be triggered by the test calling the notify() method, and then tested depending on the nature of the observer.
Questions and concerns
If all Observers need the same information when the event occurs (as in the example) then the notify() method can be parameterized. If different Observers need different information, this can be accomplished two ways:
- The observed object can pass a reference to itself, allowing each observer to call back in different ways.
- An association object can be created and populated with all information that could possible be required, and each Observer can retrieve whatever it needs.
The Observers and the observed objects might be in different process threads, or on different ends of a network connection. A Proxy can be used to cache events to improve performance if needed, or to add the remote behavior if only some Observers are remote.
More information
Visit the Net Objectives Pattern Repository: The Observer Pattern
-AMAZONPOLLY-ONLYAUDIO-START-
This is Scott Bain. Visit us at www.netobjectives.com.
-AMAZONPOLLY-ONLYAUDIO-END-