Observer Design Pattern


 definition
 UML diagram
 participants
 sample code in C#


definition

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

Frequency of use:   high

UML class diagram

participants

    The classes and/or objects participating in this pattern are:

  • Subject  (Stock)
    • knows its observers. Any number of Observer objects may observe a subject
    • provides an interface for attaching and detaching Observer objects.
  • ConcreteSubject  (IBM)
    • stores state of interest to ConcreteObserver
    • sends a notification to its observers when its state changes
  • Observer  (IInvestor)
    • defines an updating interface for objects that should be notified of changes in a subject.
  • ConcreteObserver  (Investor)
    • maintains a reference to a ConcreteSubject object
    • stores state that should stay consistent with the subject's
    • implements the Observer updating interface to keep its state consistent with the subject's

sample code in C#

This structural code demonstrates the Observer pattern in which registered objects are notified of and updated with a state change.

Show code

// Observer pattern -- Structural example




This real-world code demonstrates the Observer pattern in which registered investors are notified every time a stock changes value.

Show code

// Observer pattern -- Real World example




This .NET optimized code demonstrates the same real-world situation as above but uses modern, built-in .NET features.

Show code

// Observer pattern -- .NET optimized




  • Better Code
  • Better Career
  • Better Lifestyle

Design Pattern
Framework 2.0
TM


In C# and VB.NET



Click here for details

-- Instant Access --
Instant Download