Wednesday, March 1, 2017

Observer Design Pattern

This design pattern is typically used in publisher-subscriber scenario hence it could be implemented easily with events and delegates in C#

The idea is the publisher is event owner. Subscribers are added themselves to publishers for notification. When event occured then publisher notifies about that to every registered subscribers.

Technically, publisher owns the event handler in which list of delegates of subscribers would be called. Subscribers get their event notification through predefined common protocol i.e delegate. Publisher adds list of subscribers in its multi cast delegate. The event args are passed to subscribers through event handler at publisher.

NOTE: We can't let subscriber to take ownership of delegate as they get exposed to all other subscribers and they could modify that which violates encapsulation.

Here is the demo:
https://www.codeproject.com/Tips/769084/Observer-Pattern-Csharp

No comments: