Observer Pattern in .NET. Introduction
Tags: Programming, Events, Csharp

Introduction

I have previously written few posts about delegates, .NET Events, Events Args to show that similar to real world events, we can use this concept in our code and how useful they are in certain scenarios. In this post, we will see that those types are a good candidate for implementing observer pattern without doing anything extra. We will learn some terminologies and see a working example as well.

If you are new to .NET Events, I will suggest to read my previous posts on the topic and then discussion in this post will be more easy to follow. So lets talk about observer pattern:

Observer pattern is simply a publish/subscribe relationship.

Publisher is also refereed as the Subject is the object that we want to watch for state change.

is the object that we want to watch for state change. Then we have one or more Subscribers also refereed to as Observers. These are the dependent objects that will be notified when the state changes.

Real-World Observer

On twitter Follow capability allows up to setup an observer relationship. Whenever I follow someone on twitter, whenever that person state change (by adding a tweet), I got notified of it. Not only me, everyone who is the follower gets notified.

It turns out that if you’ve used an event handler in .NET, you have used observer pattern.

Consider observers when?

One object is dependent on the changes in another object.

Changing in one Object requires changes to many others (other object are monitoring one object).

When changes to an object should allow notification to others without any knowledge of them.

Intent and Structure

Intent

Creates a separation b/w the subject & observer

Allow multiple observers to react to changes to a single object.

Structure

Subject provides a way to Register, Un-Register and Notify.

Observer provides a way to Update.

Application Code

Before we dive into observer pattern. Lets see the current code. I created an Account class with two methods Deposit and Withdraw. Account class also have a balance property which changes when we either deposit or withdraw amount. Find below the implementation of Account.

Next, I have the following code in the Main method:

Output when running this code:

So, our application code is doing some basic work and it is very typical C# code.

New Requirements

Lets imagine that we have new requirements as follows:

As you can see that these requirements fits the need for observer pattern. If we consider our Account class as a subject, we can raise notifications whenever balance changes. On the other end, Logger and Emailer can be considered as observer which are interested in this balance change information for their operations.

Event, EventHandlers and Custom EventArgs

We can use built-in .NET Types to implement observer pattern easily. If you are new to these concepts. You can read about those on my previous posts on the same topic.

To raise notifications from Account class, I am using built-in EventHandler<T> from .NET. Then I updated the Deposit and Withdraw method to raise the events along with event-data.

I could have put the event raise code in the property-setter of Balance as well (to avoid duplicated code, but for now it is ok). So our Account class is now a subject or source of event or you can call it a publisher.

CustomEventArgs

Here is the custom EventArgs class. This class is used to pass data when event is raised.

Observers/Subscribers

Now, on the receiving end I added two classes to represent observers (or consumers) of the subject. Here is the code:

Notice that event wiring or registration is being setup in the constructor of these classes. Rest of the code is very simple and currently writing to console to simulate the operation.

So, now we have our subject which raise event (along with event-data) when balance changes and then two, observers are setup to listen for these events. With all this code in-place, lets update the Main method to see all this in action. Here is the updated code for Main method:

Now, when I run the application. The following output shows that events fired from subject and then observers are notified and the are processing those events.

Now, I will call deposit and withdraw methods multiple times to see the results:

Summary

In this post, we saw one implementation of observer pattern which uses built-in .NET types. We learned few terminologies e.g. what is subject, what is observer and also learn those are some time called as publisher , subscriber or consumer etc. If you have some comments or questions, feel free to ask. You can access the code on this URL. Till next time, Happy Coding.