Sep 10 2012

Observer Pattern in .NET

Observer Pattern? Sounds complicated? Reality is that if you are a .NET developer you already know it and it is very simple.

The observer pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
But but but I can do this with events!
Oh yes 🙂
Events (and delegates) are the idiomatic way to implement the Observer Pattern in .NET.
Nothing new then.
Let’s see an example just as a reminder.

Let’s say I want to implement a class that generate numbers every so often (this can be a class that read data from a sensor for example) and notify clients when new numbers are generated.

This a possible implementation:
Considering the new features of C# 3.5 and LINQ that made the language more functional, an another way to implement this pattern is using delegates directly. 

The are more ways to implement this pattern but you got the idea. The framework brilliantly solve this problem and these techniques are actually used heavily in many contexts.

The main advantage of using this pattern is that the resulting system is loosely coupled. In this example, the number generator know nothing about the observers.
This is an important Object Oriented Design principle: Low Coupling

Permanent link to this article: