Observer/Observable With Event-Driven Approach


The Observer design pattern falls under the category of "Behavioral Pattern". It is also called "Publish-Subscribe" pattern. This design pattern describes a one-to-many relationship between Observable (Subject) and Observer.  It means when subject changes , all Observers are notified automatically.

E.g. A company has so many employees and employees mobile number, email id are registered in the portal of company so that company can communicate with all employees at the same time. Company informs all employees immediately, when events like urgent holiday, client visit, etc. occurs. The employees can receive information in different ways like sms, email, etc.

I will explain this "Observer Design" pattern with the implementation of "Event-Driven Approach". I will not explain it in the mode of object oriented approach. So, it will be little different.

The following are the two basic objects which are involved in the Observer Design pattern:
  1. Observable (Subject): It provides a way to attach and detach Observer objects. Observer observes it.
  2. Observer: It is being notified on the change of Subject or Observable.
Observer Design pattern should be used in the following cases:
  1.  When you want to notify the object on the change of another object without knowing about these objects. 
The following is the code example in the event-driven approach:
Observable/Subject class implementation
  1. public class MyObservable  
  2. {  
  3.     public event EventHandler NotifyToObserver;  
  5.     public void EventInObservable()  
  6.     {  
  7.         EventHandler eventHandler = NotifyToObserver;  
  8.         if (eventHandler != null)  
  9.         {  
  10.             string message = "Information from Observable/Subject";  
  11.             eventHandler(message, EventArgs.Empty);  
  12.         }  
  13.     }  
  14. }  
Observer class implementation
  1. public class MyObserver  
  2. {  
  3.     public void MyObserverEvent(object sender, EventArgs args)  
  4.     {  
  5.         Console.WriteLine("Subject: {0} ", sender);  
  6.     }  
  7. }  
  1. static void Main(string[] args)  
  2. {  
  4.     MyObservable myObservable = new MyObservable();  
  5.     MyObserver myObserver = new MyObserver();  
  6.     myObservable.NotifyToObserver += myObserver.MyObserverEvent;  
  8.     myObservable.EventInObservable();  
  10.     Console.ReadLine();  
  11.  }  

Subject: Information from Observable/Subject
Some Condition in the Event-Driven Observer Design Pattern

With an Observer Design Pattern in Object Oriented Approach, any number of Observer objects will listen the changed notification. Observable/Subject doesn't have idea about Observer.
But, in an Event-Driven Observer Design Pattern, you basically have one Observer/Consuming object/method and the message what was changed or what happened in the Observable. It doesn't have any number of Observer object.