Wednesday, May 5, 2010

Observer Design Pattern By Example in C#

This is part of a series of posts in which we will deal with some of the popular design patters using simple but non-trivial examples.  The link to download the sample code is available at the bottom.

Observer design pattern consists of the the Observer Object and the Subject being observed.


This pattern is useful when the Subject object has a long running operation.  And the Observer object would like to know when certain events happen in the subject.  One solution would be for the Observer to constantly poll the subject to see what its up to.  But wouldn't it be a lot better solution if the subject can just tell you as and when it happens.

Lets tell a little story.  Your internet connection has suddenly stopped working and you call your ISP support line.  Their telephone system tells you that all its operators are busy and to wait.   The more you wait you more frustrated you get and you are not happy.   In a alternative world, your internet connection goes down and you call your ISP.  The ISP tells you that their operators are busy,  takes your contact number and promises to call you back when a support operator becomes available.  You continue to do your own work and some minutes later the ISP's support operator calls you back.  This is a far more ideal solution as you are not left hanging doing nothing.  This is what the Observer pattern achieves.

The implementation of the pattern requires that:
  • All the instance of the Observers are registered with the Subject.
  • The Subject notifies the Observer when something interesting happens.
  • An observer can also be unregistered from receiving updates from the subject.
In this example, we have the IObserver Interface.  The classes ObserverA and ObserverB implement this interface.


 The Subject class is the object we need to observe.  To facilitate this, The Subject class maintains a list of IObserver's and allows for them to be added and removed.  And when ever a certain event happens it goes the list of its observers and notifies them.

The uses of the pattern are many especially in the UI based applications where the user initiated events can be communicated to the registered observers whenever it happens. 

Download Sample Code

Happing Coding

Ravi