The Observer

Intent: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically (Gamma et al., 1994).

Example: An object is created to represent the current session of a logged-in user at a web service. Other parts of the system need to know when the session ends—and 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.

images

Figure 15: Observer example diagram.

Qualities and Principles: The observed object is decoupled from the observers—both their nature and number. Each observer has a different, single reason to sign up for notifications. The design is open-closed to new observers.

Testing: A test can use a mock observer (see p. 38) 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 (how it is designed).

Questions and Concerns: If all observers need the same information when the event occurs (as is true in the example), then the notify() method can be parameterized. If, on the other hand, different observers need different information, this can be accomplished two ways:

1)The observed object can pass a reference to itself, allowing each observer to call back in different ways.

2)An association object can be created and populated with all information that could possibly 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 (see p. 46) can be used to cache events to improve performance if needed, or to add the remoting behavior if only some observers are remote.

For more information: https://tinyurl.com/yxqggxhq

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset