8/13/2011

Design Pattern - Observer

Definition
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

UML Class Diagram

Observer: when and where use it
The Observer design pattern is one of two Gang-of-Four design patterns (the other is the Iterator pattern) that have found their way, not only into the .NET Framework libraries, but also in the .NET languages themselves. When programming a Web application or a Windows application you often work with events and event handlers.  Events and Delegates, which are first class language features, act as the Subject and Observers respectively as defined in the Observer pattern.  

The Observer pattern facilitates good object-oriented designs as it promotes loose coupling.  Observers register and unregister themselves with subjects that maintain a list of interested observers.  The subject does not depend on any particular observer, as long as the delegates are of the correct type for the event.  The event and delegate paradigm in .NET represents an elegant and powerful implementation of the Observer design pattern.

Sample
- Observer

- Concrete Observer

- Subject

- Concrete Subject

Ref: Gang of Four tutorial

No comments:

Post a Comment