Applied Design Patterns with Java

Behavioral :: Observer (293) {C ch 22}


Collaborations

Note how the Observer object that initiates the change request postpones its update until it gets a notification from the Subject. Notify is not always called by the Subject. It can be called by an Observer or by another kind of object entirely.

Consequences

The Observer pattern allows varying subjects and observers independently. Subjects can be reused without reusing their Observers, and vice versa. It allows adding Observers without modifying the Subject or other Observers.

Observer
has the following benefits and liabilities:

  1. Abstract coupling between Subject and Observer. All a Subject knows is that it has a list of Observers, each conforming to the simple interface of the abstract Observer class. The Subject doesn't know the concrete class of any Observer. Thus the coupling between Subjects and Observers is abstract and minimal. Because Subject and Observer aren't tightly coupled, they can belong to different layers of abstraction in a system. A lower-level subject can communicate and inform a higher-level Observer, thereby keeping the system's layering intact. If Subject and Observer are lumped together, then the resulting object must either span two layers (and violate the layering), or it must be forced to live in one layer or the other (which might compromise the layering abstraction).
  2. Support for broadcast communication. Unlike an ordinary request, the notification that a Subject sends needn't specify its receiver. The notification is broadcast automatically to all interested objects that subscribed to it. The Subject doesn't care how many interested objects exist; its only responsibility is to notify its Observers. This gives the freedom to add and remove Observers at any time. It's up to the Observer to handle or ignore a notification.
  3. Unexpected updates. Because Observers have no knowledge of each other's presence, they can be blind to the ultimate cost of changing the Subject. A seemingly innocuous operation on the Subject may cause a cascade of updates to Observers and their dependent objects. Moreover, dependency criteria that aren't well-defined or maintained usually lead to spurious updates, which can be hard to track down. This problem is aggravated by the fact that the simple update protocol provides no details on what changed in the Subject. Without additional protocol to help Observers discover what changed, they may be forced to work hard to deduce the changes.

Catalog Behavioral Prev Next