Today I will go through with “Observer Patter”, where I will try to explain a simple example of this pattern as well as implementation and use.
First come to what is Observer Patter, as per Wikipedia the general definition of Observer pattern is as bellow:
“The observer pattern (a subset of the publish/subscribe pattern) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.”
The UML diagram of basic observer pattern is as bellow:
How actually this pattern works?
Well as per the above definition we have 2 types of objects one is Subject and other one is Observer. A Subject maintain a list of Observe objects and notify those when property of subject changes.
Example:
Suppose we are maintaining stock exchanges data and we have number of securities agencies. Those securities consume our stock’s data as per there need. When they what to consume data, they register in our system and unsubscribe when they are needed. Here the catch is, they are always updated for each stock’s data change.
In the following C# code example I will try to pull out the gist of Observer pattern as per our above description.
In the code example I have taken 2 interfaces and 3 concrete classes of which 1 interface and 2 concrete classes are of Observer’s & 1 interface and 1 concrete class of Subject’s.
IObserver Interface:
This interface contains 2 method signatures. One is Update and another is ShowData.
using System.Collections.Generic; namespace ObserverPatter { interface IObserver { void Update(Dictionary<string, float> stocks); void ShowData(); } }
This class implements the IObserver interface. The Update method changes the property of stocks information with the new stocks information and ShowData makes the new stock information visible.
using System; using System.Collections.Generic; namespace ObserverPatter { class FirstObserver : IObserver { private Dictionary<string, float> _stocks; public void Update(Dictionary<string, float> newData) { this._stocks = newData; this.ShowData(); } public void ShowData() { Console.WriteLine("First Securities LTD"); foreach( KeyValuePair<string,float> data in _stocks) { Console.WriteLine("Current price of {0} is now {1}",data.Key,data.Value); } } } }
This class is also act as previous one. We are taking this class just to show as second observer which will be a subscriber of the server and will be unsubscribe latter.
using System; using System.Collections.Generic; namespace ObserverPatter { class SecondObserver : IObserver { private Dictionary<string, float> _stocks; public void Update(Dictionary<string, float> newData) { this._stocks = newData; this.ShowData(); } public void ShowData() { Console.WriteLine("Second Securities LTD"); foreach (KeyValuePair<string, float> data in _stocks) { Console.WriteLine("Current price of {0} is now {1}", data.Key, data.Value); } } } }
ISubject Interface:
This interface contains 3 main method's signature 1.RegisterObserver 2.RemoveObserver 3.NotifyObservers
RegisterObserver method register an observe in subject’s observer list.
RemoveObserver method unregister an observer from the subject’s observer list.
NotifyObservers method is responsible to notify all objects which are subscribed to the server .
namespace ObserverPatter { interface ISubject { void RegisterObserver(IObserver o); void RemoveObserver(IObserver o); void NotifyObservers(); } }
StockSubject concrete class:
We have implemented ISubject interface in this class and proceeded accordingly.
using System.Collections.Generic; namespace ObserverPatter { class StockSubject : ISubject { private List<IObserver> _observers = new List<IObserver>(); private Dictionary<string, float> _stocks; public void RegisterObserver(IObserver o) { _observers.Add(o); } public void RemoveObserver(IObserver o) { _observers.Remove(o); } public void NotifyObservers() { foreach(IObserver observer in _observers) { observer.Update(_stocks); } } public void setStockPriceInformation(Dictionary<string,float> newData) { this._stocks = newData; this.NotifyObservers(); } } }
Now in the runner class “Program” we have implemented our application where we have added two observers and letter removed one observer at runtime.
using System; using System.Collections.Generic; namespace ObserverPatter { class Program { static void Main(string[] args) { StockSubject stockSubject = new StockSubject(); var firstObserver = new FirstObserver(); var secondObserver = new SecondObserver(); stockSubject.RegisterObserver(firstObserver); stockSubject.RegisterObserver(secondObserver); var dataSet = new Dictionary<string,float>(); dataSet.Add("Google Inc", 500.25f); dataSet.Add("Micorsoft",400.15f); stockSubject.setStockPriceInformation(dataSet); dataSet.Clear(); dataSet.Add("Google Inc", 330.25f); dataSet.Add("Micorsoft", 550.15f); stockSubject.RemoveObserver(secondObserver); stockSubject.setStockPriceInformation(dataSet); Console.ReadKey(); } } }
Output :
Ok that’s it for today . Let me know if you have any concern regarding this pattern or code.
No comments:
Post a Comment