Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observer design pattern and C# event delegate model

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

like image 245
123Developer Avatar asked Jun 23 '10 17:06

123Developer


3 Answers

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).

like image 108
Reed Copsey Avatar answered Oct 04 '22 20:10

Reed Copsey


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

like image 25
Derick Bailey Avatar answered Oct 04 '22 22:10

Derick Bailey


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.

like image 23
decyclone Avatar answered Oct 04 '22 20:10

decyclone