Please enable JavaScript.
Coggle requires JavaScript to display documents.
Observer (Implementation (Avoiding observer-specific update protocols:…
Observer
Implementation
Making sure Subject state is self-consistent before notification: If subclass overrides method and calls superclass which calls notify() then state could be inconsistent since sub-class did not finish. Use Template Method pattern with notify at end of call.
-
Dangling references to deleted subjects: When subject is deleted, observer should be notified so they can remove reference to subject
Specifying modifications of interest explicitly: Observers can register with subject with "Aspects" of interest so they are notified selectively
Who triggers the update? 1) Methods that change state in subject can call notify. Removes burden from clients but could result in lot of calls. 2) Client can call notify after all state changes, but now client needs to know this and could forget
Encapsulating complex update semantics: When there are multiple subjects and notification should happen after all subjects have changed then a ChangeManager class can be used to handle notification
Observing more than one subject: If observer observes more than one subject, then subject can pass itself in update() method to let observer know which subject changed
Combining the Subject and Observer classes: Where multiple inheritance is not allowed, subject and object can be combined into one interface
Mapping subjects to their observers: Subjects keep reference to Observers. If this takes space, can use a HashMap.
Consequences
Abstract coupling between Subject and Observer - Subject has a list of Observers that implements an interface, so it does not know anything about concrete subjects
Support for broadcast communication. Subject notifies all interested observers. Observers responsibility to decide whether to act on it or not
The Observer pattern lets you vary subjects and observers independently. You can reuse subjects without reusing their observers, and vice versa
Unexpected updates - Spurious updates to subject could cause cascading changes to objects and their dependent objects
-
Key Objects
Subject
Has dependent observers which are notified when subject changes. Subject can also be changed by other Observers or another object
Observer
Maintain reference to subject. When notified of change, query subject to get state
Intent
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
AKA
Dependents, Publish-Subscribe
Motivation
When you have related classes that need to be maintained consistent but you want to avoid close coupling.
-