Learn the Observer Pattern:

I am starting to write a series of blog post which would be named “Learn {tagline}…..”
In these series I would post things about design pattern, programming methodologies, skills etc etc

For today, I will start with my favorite Design Pattern. The Observer Pattern.

I would first state out what the GoF book, states as the intent of this pattern.

Intent

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

Applicability of this pattern

  • When a change to one object requires changing others, and you don’t know how many objects need to be changed
  • When an object should be able to notify other objects without making assumptions about who these objects are. (Loosely coupled objects)
  • When an abstraction has two aspects, one dependent on the other.

UML Structure

observerpattern

Sample Code

I am going to write a sample application using WPF to show how to use the pattern. One may say its an overkill but it does show loose coupling.

First our pattern, our class diagram would look like this

classdiagram1

Our Interface ISubject and our Concrete Subject implementation

 

Next the interface for IObserver

 

Now that we got the pattern in place, let start with creating two UserControl in WPF, we will create an English and Turkish Label Control that implements the IObserver interface, as shown in the class diagram below
classdiagram12
English and Turkish Label Control implementation

 

Simple nothing fancy about these 2 controls other than the Turkish one, which has English -> Turkish hard coded translation.

Now lets see how the WPF app looks like and how it hooks it all up.

 

Application Screen shot

observerapp

Conclusion
Our main WPF app hooks the EnglishControl and TurkishControl with the Concrete Subject by using poor man’s Property Injection in the Default Constructor of the App. When a button is clicked on the App it sets the Subject State to a random English word from the list. This in turns calls the Notify on the Subject and it will then notify all its IObservers.

Additionally I would like to mention that we have used the pull method. Where we request to get the state from the subject, we could also use the push method where the subject will sends details information about the change to the observer. The push method makes the observer less reusable, because Subject class makes assumptions about the Observer classes that might not always be true. I suggest one to use the pull method whenever possible.

Once you understand the Observer Pattern concept, it is very easy to implement your own Events, the basic idea of Events is the Observer Pattern. In my next post I will show you how to use Events and Delegates to implement Observer Pattern in C#

You can also download the entire source code.

Hope you enjoy the first series of the Learn topics, will be posting more in the future.