Observer Design Pattern
The Gang of Four book (Design Patterns: Elements of Reusable Object-Oriented Software, 1995) says that the 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". In this article, we will learn what the observer design pattern is and how to implement the observer design pattern in a C# and .NET application.
Purpose of Observer Pattern
The Observer pattern is to notify the interested observers about some change occurred. We can add more observers in runtime as well as remove them.
Example: We have a form to select the color. For each color change we need to update the entire application. There will be observers listening to the color change event for updating themselves.
Subject and Observers
The two important key terms in the pattern are the Subject and the Observer.
The Subject is the object which holds the value and takes responsibility in notifying the observers when the value is changed. The subject could be a database change, property change or so.
We can conclude that the subject contains the following method implementations.
- public interface ISubject
- {
- void Register(IObserver observer);
- void Unregister(IObserver observer);
- void Notify();
- }
- public interface IObserver
- {
- void ColorChanged(Color newColor);
- }
There will be only one Subject and multiple number of Observers.
Registering and Unregistering
In the above interface, the observer can use the Register() method to get notified about changes. Anytime, it can unregister about notifications using the Unregister() method.
Notifying
The Notify() method will take care of calling the listening observers.
Associations
The Subject and Observer objects will be having a one-to-many association.



Join the conversation! Your thoughts help the community grow.