Tuesday, May 29, 2012

Design Pattern - Observer

http://en.wikipedia.org/wiki/Observer_pattern
Intent:
  1. Define one-to-many dependency between objects so that when one objects changes state, all its dependents are notified and updated Automatically
  2. Dependents, Publish-Subscribe, Model-View
Applicability:
  1. When an abstraction has two aspects, one dependent on the other.
  2. When a change to one object requires changing others without being coupled.
Structure:

Participants:
Subject
  1. knows its observers.
  2. any number of Observer objects may observe a subject.
  3. provides an interface for attaching and detaching Observer objects.
Observer
  1. defines an updating interface for objects that should be notified of changes in a subject.
ConcreteSubject
  1. stores state of interest to ConcreteObserver objects.
  2. sends a notification to its observers when its state changes.
ConcreteObserver
  1. maintains a reference to a ConcreteSubject object.
  2. stores state that should stay consistent with the subject's.
  3. implementes the Observer updating interface to keep its state consistent with the subject's.
Overview:
  1. ConcreteSubject notifies its observers whenever a change occurs that could make its observers' state inconsistent with its own.
  2. After being informed of a change in the concrete subject, a ConcreteObserver object may query the subject for information.
  3. ConcreteObserver uses this information to reconcile its state with that of the subject.
  4. Abstract coupling between Subject and Observer.
  5. Support for broadcast communication.
  6. Unexpected updates.
Applications:
Document - View architecture
  1. Document is responsible for data
  2. View is responsible for representing data
  3. There can be multiple type of document and view
  4. Any view can be interested in tracking changes in any document

No comments: