Introduction
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:
- Observable (Subject): It provides a way to attach and detach Observer objects. Observer observes it.
- Observer: It is being notified on the change of Subject or Observable.
Observer Design pattern should be used in the following cases:
- 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
- public class MyObservable
- {
- public event EventHandler NotifyToObserver;
-
- public void EventInObservable()
- {
- EventHandler eventHandler = NotifyToObserver;
- if (eventHandler != null)
- {
- string message = "Information from Observable/Subject";
- eventHandler(message, EventArgs.Empty);
- }
- }
- }
Observer class implementation
- public class MyObserver
- {
- public void MyObserverEvent(object sender, EventArgs args)
- {
- Console.WriteLine("Subject: {0} ", sender);
- }
- }
Execution
- static void Main(string[] args)
- {
-
- MyObservable myObservable = new MyObservable();
- MyObserver myObserver = new MyObserver();
- myObservable.NotifyToObserver += myObserver.MyObserverEvent;
-
- myObservable.EventInObservable();
-
- Console.ReadLine();
- }
Output
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.