Implementing observer pattern

Introduction:

While I was developing a new web application in our company I found that every entity in the system has some shared fields which holds data about when and who saved this entity into the system. Basically those fields were CreationDate, CreatedBy, LastModificationDate, LastModificationBy and EntityId for sure.

There are multiple approaches to solve this situation:

1. In every user control include these fields and reflect data to them directly: but this will force you to write more duplicated code. And this will make update and maintenance more complicated and error frequent process. Imagine that you have 10 controls this means you need to do 10 updates if any update is needed in the entity details.

2. Create a user control called details and place those fields in it and access those fields directly from each entity screen: although this will ease maintenance and updates this approach has a disadvantage which that those controls are now tightly coupled.

Applications with tightly coupled classes tend to be brittle and difficult to maintain, because changes in one class could affect all the tightly coupled classes.

The problem: How can user controls -objects- notify other controls –objects- of state changes without being dependent on their classes?

3. Using observer pattern and create loosely coupled controls to communicate between each other without depending in their classes.

In this article I will show how to a build simple user control that implements observer pattern to handle updates and passing notifications around to update a set of objects when some important event has occurred.

Background:

The observer pattern is categorized under Behavioral Patterns. Behavioral Patterns is those patterns are concerned with algorithms and the assignment of responsibilities between objects. Behavioral patterns describe not just patterns of objects or classes but also the patterns of communication between them.

So what is observer pattern?

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

What is Subject? What is observer?

Subject: is the object which wills frequently changes his state from time to time. And there is another objects depends on it.

Observer: is the object which depends on a subject keep eye on updates at his subject state.

Here’s how it works:

An observer signs up to receive notifications of changes to the subject.

clip_image002

A second observer can register itself too. In fact a subject may have any number of dependent observers. Observers are not aware of presence of each other.

clip_image004

When certain event occurred all observers are notified.

clip_image006

An observer can unregister itself from subject so he will never receive notifications from subject.

clip_image008

With this generic way of communicating between the subject and observers, collaborations can be built dynamically instead of statically. The code is now much more separate, and thus easier to maintain and reuse. There is no direct dependency between subject class and observer class.

clip_image010

In our example Address_UC is a ConcreteSubject and RecordDetails_UC is one of it ConcreteObservers, so when the domain object associated with Address_UC class has changed the RecordDetails_UC class will be notified and handles this event in a proper way. I will show how explicitly implement observer pattern and another time by using delegates and events.

Implementing Subject class:

You can implement Subject class as super class or abstract class. But due the limitation in some languages like C#,VB.Net that class can inherits only one. This will cause a problem because most of domain objects are inherits from domain objects. So our subject class will be implemented using interface. Remember that class can implement many interfaces.

public interface ISubject 
{
List<IObserver> ObserversList {get;}
void AttachObserver(IObserver observer);
void DeAttachObserver(IObserver observer);
void NotifyObservers();
}

Basically our Subject interface contains methods to attach, deattach and notify observers. And each ConcreteSubject class – means class that implement the subject interface - should define a list of ConcreteObservers.

Implementing observer class:
public interface IObserver

{

void Updateobject(ISubject subject);

}

The observer class is very simple and contains a method that allowed subjects to notify it.

All we need know is to implement ISubject methods in our ConcreteSubject “Address_UC” as simple as this:

#region ISubject Members 
public List<ObserverTutorial.App_Code.IObserver> ObserversList
{
get { return this.m_ObserversList; }
}
public void AttachObserver(ObserverTutorial.App_Code.IObserver observer)
{
this.ObserversList.Add(observer);
}
public void DeAttachObserver(ObserverTutorial.App_Code.IObserver observer)
{
this.ObserversList.Remove(observer);
}
public void NotifyObservers()
{
foreach (App_Code.IObserver observer in this.ObserversList )
{
observer.Updateobject(this);
}
}
#endregion

Note that NotifyObservers method will be called form another method in the Address_UC when an certain event occur something like after user save domain object data:

protected void btnOk_Click(object sender, EventArgs e) 
{
bool result = SaveEntityData();
/// After Subject object data is saved in a state notify observers
if (result)
{
this.NotifyObservers();
}
}

In the ConcreteObserver “RecordDetails_UC” the implementation of the IObserver lonely method Updateobject allow Address_UC to notify RecordDetails_UC that it has changed and passing itself as parameter so RecordDetails_UC can update his state too in a proper way. But firstly RecordDetails_UC needs to register itself with Address_UC:

ISubject Subject = this.Parent as ISubject; 
if (Subject != null)
{
Subject.AttachObserver(this);
}
Are we smarter than Microsoft so they does not have observer pattern implemented yet?

Microsoft .NET Framework defines the notion of delegates and events to accomplish the Observer role. Therefore, you would rarely implement the Observer pattern explicitly in .NET, but should use delegates and events instead. I attached implementation of this sample using delegates and events too.

You can download the tutorial file from the attachments here ...

9 Comments

  • just a small remark... DeAttach? how about Detach? ;)

    the observer is a quite useful pattern, however when using .NET i really prefer events and delegates to do that work for me... if it's in the language/framework, why would one not choose to use it?

  • Anywhere better to put that .NotifyObserver method? i don't want to have to writ ethat everywhere my object gets updated. Maybe just call it in SaveEntityData itself?

  • Nice post -- very clear and good examples.

  • Can I get your zip examples. The zip file is corrupt.

    thanks,
    onisick@charter.net

  • I like the idea of combining delegates to the pattern...

    However, your zip is corrupted, as pointed out.

  • Hi,
    simple and Good explanation do you have working copy as the attachment is corrupt

  • The attached file is not corrupted .. I download it and it work fine

  • how do i persist my data in the AddressEntity (Enity) object, let say if i want to have that object in my .aspx page how would i do that?

    in my default.aspx, i have added another button and when i click that button i want to have the data in the object how would i do that?

    here is what i have done so far:

    in the default.aspx page i have added this code:



    object x = this.ViewState["Entity"];

    everytime i get null value ?

    what i'm trying to do is to keep my object (entity) alive regardless in which page i'm in, how would i do that?

    thanks.

  • Implementing observer pattern.. Huh, really? :)

Comments have been disabled for this content.