Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegates vs. Observer patterns [closed]

Are there any guidelines on when you should use a delegate for indirect association, and an observer?

In C#, you get to use delegates for simple call-backs. I guess pointers to function and pointers to member functions can be considered as delegates too (am I right?).

I realize that do use an observer, you need to create an interface, and implement it, so it is more strongly-typed and the relationship is more formal. For a delegate, as long as the function signature and accessibility matches, you can "hook them up".

Does delegates make the observer pattern moot? How do you decide on a delegate vs. an observer pattern?

like image 297
Extrakun Avatar asked Apr 07 '11 15:04

Extrakun


1 Answers

The observer pattern is already implemented for you in the form of events.

The advantage of events is that they can have multiple subscribers, while with a delegate, you can only have one. This makes events much better for public interfaces, and scenarios where you don't have complete control over who wants to get notified that something happens. In reality, events are just automatically managed lists of delegates. You'll have to see what makes more sense in your scenario.

Edit: As commenter Rabbi mentions, the above isn't entirely true, as any delegate can become a multicast delegate. The purpose of the event modifier is to make a delegate that can only be invoked inside the class that defines it. This is most useful for ensuring encapsulation in public interfaces.

like image 94
Alex J Avatar answered Sep 30 '22 02:09

Alex J