Observer Pattern in Java and C#
December 12, 2007 by Daniel Hoelbling
Since yesterday I am reading my brand new Head First - Design Patterns and really enjoy doing so. The book is funny, informative and it's quite unique style really ... works.
Most articles I read on Design Patterns where (while informative) really hard to understand and made them a pain to read. So I was thrilled to find a book that was entertaining and informative.
So, I tried some of that stuff out. Obviously I didn't make it past Chapter 2 till now and am still working on the Observer Pattern.
The samples in the book are all in Java, so I immediately tried to translate them to C#.
I looked for the Observable-Class in the .NET Framework, no clue.
I searched the Web, and it looked like C# has no built-in support for the Observer Pattern. Even Wikipedia has a C# Example on their Observer Pattern page that is just a plain rewrite of the standard Java Examples. But still no sign of something like an Observable-Class.
Until I figured out that the Observer Pattern is hardcoded into the C# Language as part of their Event System using an Event Pattern!
This is the usual Observeable Class. 3 Methods (Attach, Detach and Notify) and one function to send out the Notification (In Java it would set the Observeable.setChanged-Method and should also change a State)
Now, this is the Implementation for our Subject I came up with after applying the Event Pattern:
So, hell yes this looks simpler doesn't it?
The only catch is that you can't fire the Notify event if there are no subscribers because in that case it is null. That's why you need to check it before firing.
But how does this thing work for our Observer (Subscriber)?
Here is the Code that would Observe the standard Java-like Observer:
Note that this Class uses .Attach to subscribe to our Subject.
While the C# implementation just hooks up an event to a function.
That function doesn't need be called update() as the above, it has only to match the delegate we defined in our subject!
So. The implementation of an Observer Pattern in C# is basically 3 lines of code.



