views:

2022

answers:

6

After reading the Head First Design Patterns book and using a number of other design patterns, I'm trying to understand the Observer pattern. Isn't this already implemented using Events in the .NET Framework?

+10  A: 

Yes, it is. The observer pattern is also called the publish/subscribe pattern, which is exactly what events allow you to do.

Sander
+4  A: 

That's right, events are an implementation of the observer pattern. I have read discussions , though, of people who still write their own, to give them either more flexibility, or maybe just to avoid the event-raising syntax.

Ben Scheirman
+2  A: 

Yes, it's identical.

A note: if you really want to understand events, I recommend learning the observer pattern and implementing it yourself a for a while. Once you fully understand it, stop doing it yourself and use the professional and well-documented implementation unless you have a real need to do otherwise.

Dinah
+8  A: 

I would say yes, it was Anders Heljsberg's intent to make the observer pattern a first-class language feature with events in C#, based on his experience with Delphi. Anders makes this and other design intentions clear in an excellent interview on Software Engineering Radio.

flipdoubt
A: 

Most modern languages have native support for some of the design patterns. It has been argued that languages are better the more patterns they support natively without the need to implement them explicitly, and that Lisp is excellent in this regard. Jeff had something to say about that, too.

Konrad Rudolph
+1  A: 

Yes, but programming the observer pattern explicitly and thus not using delegates and events can result in easier debugging of your code.

Consider the difference:

public void NotifyObservers()
{
    foreach(Product product in ProductList)
    {
        if (product is IProductObserver)
        {
               product.Update(this)
        }
    }
}

Here it is very clear what products in the list get notified of a change. While debugging you can inspect the ProductList...

With using delegates and events it can be more cumbersome to find out how many "delegates" were actually "subscribed" to handle the event.

Hace
I don't like the idea of encouraging developers to reimplement instead of reuse.
Jay Bazuzi
Can you elaborate on that? I mean, In both cases developers have to implement the pattern. I have put this as an explicit example basicly because I am agreeing with Dinah that if you really want to understand the observer pattern it is best to first build it yourself and go to events afterwards.
Hace