Observer Pattern Using Delegates v/s Observer Pattern Using Events and Delegates
Most of the articles and texts in C# demonstrate the observer pattern using events and delegates. When going through one such text, a thought come across my mind. Why we are going for events when we can easily achieve the multicasting using Delegates alone. After some R&D, I found it out why and hence this blog post.
I am going to explain this “why” using a Weather Station example. To keep things simple, the Weather Station that we are going to see will keep track of only the temperature. Whenever the temperature changes, it simplify notifies its subscribers with the new temperature. Flash News is one of the subscribers which show the temperature in flash news. News Feed, another subscriber which adds the temperature information to the news feed. Fine, enough theory! It’s time to see the code.
Here is the implementation of Observer Pattern using Delegates alone.
The Main Program
Hurrah! It’s working as expected. Both subscribers are get notified. We can implement the observer pattern using delegates alone. Stop for a minute and go through the code, is the implementation robust? Kudos if you are able to find the shortcomings of this implementation. If not continue reading.
Think of a world where everyone is good. There is no need of police, no need of court either. But it is not the case. You may wonder why I am mentioning this here. This analogy holds true for the objective of this blog post too. There is no need of using events in the c# programming world if all the subscribers are good. Miserably, here also it is not the case. Hence we are going for events instead of using delegates alone.
Drawbacks of using delegates alone
A subscriber can replace other subscribers by reassigning the delegate
A subscriber can clear all other subscribers also (by setting the delegate to null).
A subscriber can broadcast to other subscribers by invoking the delegate
Clearly all the above 3 drawbacks violates the Observer Pattern.Here is our evil subscriber code implementation.
Hope now you understand the need of a better implementation of observer pattern. Here comes the salvage. Event! Use event along with delegates. With event in place, compiler will not allow the evil subscriber to get compiled.
Robust implementation of Weather Station using events
The unfortunate evil subscriber no longer compiles with events!