Thursday, April 7, 2011

Design Pattern: Observer

The Observer defines a one to many relationship, so that when one object changes state, the others are notified and updated automatically.

The Observer design pattern is about passing notifications around to update a set of objects when some important event has occurred. You can add new observer objects at runtime and remove them as needed. When an event occurs, all registered observers are notified. Below Figure shows how it works; an observer can register itself with the subject.

image
And another observer, Observer 2, can register itself as well, as shown in below figure

image

Now the subject is keeping track of two observers. When an event occurs, the subject notifies both observers.

image

Illustration:

Picture1

Solution:

The observer pattern describes how to establish these relationships. The key objects in this pattern are subject and observer.

  • A subject may have any number of dependent observer.
  • All observers are notified whenever the subject undergoes a change in state.
  • In response, each observer will query the subject to synchronize its state with the subject’s state.

Applicability:

Use the Observer pattern in any of the following situations:

  • When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.
  • When a change to one object requires changing others, and you don’t know how many objects need to be changed.
  • When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don’t want these objects tightly coupled.

Structure

image

Collaborations

  • ConcreteSubject notifies its observers whenever a change occurs that could make its observers’ state inconsistent with its own.
  • After being informed of a change in the concrete subject, a ConcreteObserver object may query the subject for information. ConcreteObserver uses this information to reconcile its state with that of the subject.

Consequences

  • Abstract coupling between Subject and Observer
  • Support for broadcast communication.
  • Unexpected updates

Model

image

No comments: