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, such as, generics, reflection, object initializers, automatic properties, etc.

Show code

// Observer pattern -- .NET optimized




   Better Code 
   Better Career 
   Better Lifestyle 


.NET
Design Pattern
Framework 4.5


 
C# and VB.NET


   Includes:

  Gang of Four Patterns
  Head First Patterns
  Enterprise Patterns
  Multi-Tier Patterns

  Repository Pattern
  Unit-of-Work Pattern
  CQRS Pattern
  Active Record Pattern

  Model View Controller
  Model View Presenter
  Model View ViewModel

  SparkTM RAD Platform
  Art Shop MVC Application
  Much more...

Click here for details

-- Instant Access --
Instant Download