In the delegate pattern, only one object can directly listen to another object's events. In the observer pattern, any number of objects can listen to a particular object's events. When designing a class that needs to notify other object(s) of events, why would you ever use the delegate pattern over the observer pattern? I see the observer pattern as more flexible. You may only have one observer now, but a future design may require multiple observers.
|
|
You're looking at things incorrectly. An observer sees that a particular event occurs. It does not impact it, or own it. A delegate handles a particular event, and has ownership of the handler, even if the delegator owns the interface to the event. |
|||||||||||||
|
|
There is no delegate pattern per se. I am going to assume you mean Delegation Pattern. As I understand it, they're the complete reverse of each other and used for different purposes. Generally, with an Observer Pattern, any number of observer objects will listen to an event on a second object and act on the event. The second object has no knowledge of its listeners. It just calls out to them. A delegate object is passed to the second object which calls methods directly on the delegate. And therein lies the advantage you're looking for. Rather than sending a single message to multiple listeners, it has complete control over a single object (at a given time). See also Inversion of Control. |
|||
|
|
|
The delegate pattern, as I understand you, is know as the event handler mechanism in other languages, for example Delphi. As such it simply is an implementation of the observer pattern with a major restriction: only one listener at a time. The disadvantage of event handlers or delegates is obvious: only one observer. The advantage is not so obvious: performance. With an observer pattern you can add many observers. When an event occurs that the observers need to be notified about, you will need to enumerate the observers and send a notification to each. This can quickly bog down any observed instance, especially when the number of events that require notification is significant as well. |
|||||||||
|
|
That's a question of several trade-offs. Trade-offs:
Delegate pattern:
Observer pattern:
|
|||
|
|
