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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With