It seems that the observer design pattern is in built in C# through its event delegate model. Is there any reason where I may have to implement it in the classical way?
regards
123Developer
Typically, the event model built into the language will be sufficient for the observer pattern. There is really no reason to implement it in a different way, since you're just recreating events.
That being said, there are rare times when people change the "standard" event pattern. For example, I have seen cases where people want to raise events asynchronously. I typically don't recommend this (I, personally, think this is better handled on the subscriber's side), but it still can be handled via a standard C# event, but raising the event changes slightly (using GetInvocationList and asynchronously calling the delegates).
you're correct. the observer pattern is implemented in the C# event system, using delegates.
the #1 reason you would want something closer to a classic observer is even aggregation to facilitate domain events and/or composite application architectures.
jeremy miller has a great post on event aggregator: http://codebetter.com/blogs/jeremy.miller/archive/2009/07/21/braindump-on-the-event-aggregator-pattern.aspx
and i used his post to create my event aggregator which i put into a messaging-based architecture for my winforms / handheld apps: http://www.lostechies.com/blogs/derickbailey/archive/2009/12/22/understanding-the-application-controller-through-object-messaging-patterns.aspx
I think generally there is no real reason why we should not use C# delegate model to implement the Observer pattern. But, in .Net 4, they added IObserver<T>
and IObservable<T>
interfaces to implement push based notification system. So, I guess that is one of the cases where you would want to use the interfaces rather than the event based model.
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