The Observer pattern is intended to provide you with a means to present data in several different forms at once so that when one object changes state, all its dependents are notified and updated automatically.

observer-pattern

The Observer pattern can be found everywhere. Mostly it is used when you have more than one view on the same data. For example, a list view and a detail view.

In the client, a couple of observers are attached to their subject of interest. As soon as the state of the subject changes, all observers are notified that there is a change of state.

The abstract parent class Subject contains a list of observers and methods necessary for attaching and detaching observers. Most important method is notify which traverses the list and notifies all attached observers.

The concrete child class contains a certain state, which can be virtually anything. In this example, something simple. Just a string containing im-por-tant information.

All observers need some way to update their state when they are notified. This is done by implementing the Update method of abstract class Observer.

The concrete observer implements the abstract update method, plus its own methods.

When you think about the problem this pattern solves, you probably agree with me that this is a relatively simple but powerful pattern.

This post is part of a series on the foundational design patterns in C#. In this series we explore the ancient design patterns and their use in real-world programming situations of today. In these series of posts we explore each pattern by looking at a minimalistic example to reveal its structure and then look at more concrete and useful real-world C# code that implements the pattern.