Skip to main content

Observer Pattern With C# 4.0

Observer Pattern
"The Observer Pattern Defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically."
Publishers + Subscribers = Observer Pattern

C# Introduced , IObserver<T> and IObservable<T> which will help push-based notification,also known as the observer design pattern. The IObservable<T> interface represents the class that sends notifications (the provider); the IObserver<T> interface represents the class that receives them (the observer). T represents the class that provides the notification information.

An IObserver<T> implementation arranges to receive notifications from a provider (an IObservable<T> implementation) by passing an instance of itself to the provider's IObservable<T>.Subscribe method. This method returns an IDisposable object that can be used to unsubscribe the observer before the provider finishes sending notifications.

The IObserver<T> interface defines the following three methods that the observer must implement:
The OnNext method, which is typically called by the provider to supply the observer with new data or state information.

The OnError method, which is typically called by the provider to indicate that data is unavailable, inaccessible, or corrupted, or that the provider has experienced some other error condition.
The OnCompleted method, which is typically called by the provider to indicate that it has finished sending notifications to observers.




WeatherData.cs
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 namespace ObserverPatternInCsharp  
 {  
   public class WeatherData  
   {  
     private float temperature;  
     private float humidity;  
     private float presssure;  
     public WeatherData(float temp,float hum, float press)  
     {  
       temperature = temp;  
       humidity = hum;  
       presssure = press;  
     }  
     public float Temperature  
     {  
       get { return this.temperature; }  
     }  
     public float Humidity  
     {  
       get { return this.humidity; }  
     }  
     public float Presssure  
     {  
       get { return this.presssure; }  
     }  
   }  
 }  
WeatherProvider.cs
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 namespace ObserverPatternInCsharp  
 {  
   public class WeatherProvider: IObserver<WeatherData>  
   {  
     private IDisposable unsubscriber;  
     private string instName;  
     public WeatherProvider(string name)  
     {  
       this.instName = name;  
     }  
     public string Name  
     {  
       get { return this.instName; }  
     }  
     public virtual void Subscribe(IObservable<WeatherData> provider)  
     {  
       if (provider != null)  
         unsubscriber = provider.Subscribe(this);  
     }  
     void IObserver<WeatherData>.OnCompleted()  
     {  
       Console.WriteLine("The Provider has completed transmitting data to {0}.", this.Name);  
       this.Unsubscribe();  
     }  
     public virtual void Unsubscribe()  
     {  
       unsubscriber.Dispose();  
     }  
     void IObserver<WeatherData>.OnError(Exception error)  
     {  
       Console.WriteLine("{0}: The provider cannot be read data.", this.Name);  
     }  
     void IObserver<WeatherData>.OnNext(WeatherData value)  
     {  
       Console.WriteLine("{3}: The current Weather is Temperature: {0}, Pressure {1}, Humidty {2}", value.Temperature, value.Presssure, value.Humidity,this.Name);  
     }  
   }  
 }  
WeatherSubscriber.cs
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 namespace ObserverPatternInCsharp  
 {  
   public class WeatherSubscriber : IObservable<WeatherData>  
   {  
     private List<IObserver<WeatherData>> observers;  
     public WeatherSubscriber()  
     {  
       observers = new List<IObserver<WeatherData>>();  
     }  
     public IDisposable Subscribe(IObserver<WeatherData> observer)  
     {  
       if (!observers.Contains(observer))  
         observers.Add(observer);  
       return new Unsubscriber(observers, observer);  
     }  
     private class Unsubscriber : IDisposable  
     {  
       private List<IObserver<WeatherData>> _observers;  
       private IObserver<WeatherData> _observer;  
       public Unsubscriber(List<IObserver<WeatherData>> observers, IObserver<WeatherData> observer)  
       {  
         this._observers = observers;  
         this._observer = observer;  
       }  
       public void Dispose()  
       {  
         if (_observer != null && _observers.Contains(_observer))  
           _observers.Remove(_observer);  
       }  
     }  
     public void SetMeasurements(WeatherData weather)  
     {  
       foreach (var observer in observers)  
       {  
         if (weather == null)  
           observer.OnError(new WeatherUnKnnowException());  
         else  
           observer.OnNext(weather);  
       }  
     }  
   }  
 }  
WeatherUnKnnowException.cs
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 namespace ObserverPatternInCsharp  
 {  
   public class WeatherUnKnnowException: Exception  
   {  
     internal WeatherUnKnnowException()  
     { }  
   }  
 }  
Program.cs
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 namespace ObserverPatternInCsharp  
 {  
   public class Program  
   {  
     public static void Main()  
     {  
       WeatherSubscriber subscriber = new WeatherSubscriber();  
       WeatherProvider NDTVProvider = new WeatherProvider("NDTV");  
       NDTVProvider.Subscribe(subscriber);  
       WeatherProvider TimesProvider = new WeatherProvider("Times");  
       TimesProvider.Subscribe(subscriber);  
       WeatherProvider HeadLineProvider = new WeatherProvider("HeadLine");  
       HeadLineProvider.Subscribe(subscriber);  
       subscriber.SetMeasurements(new WeatherData(10, 7, 14));  
       HeadLineProvider.Unsubscribe();  
       subscriber.SetMeasurements(new WeatherData(28,26, 14));  
       subscriber.SetMeasurements(null);  
       Console.Read();  
     }  
   }  
 }  

Comments

Popular posts from this blog

Localization in Umbraco, Item Page field localization

Umbraco is one of the most deployed Web Content Management Systems on the Microsoft stack. It's in the top five most popular server applications and among the ten most popular open source tools in general. You can directly download and start using it from http://www.umbraco.com If you have not used the application yet, its always worth trying it once. I am sure you will love it. Well, for the first time users, Umbraco provide step by step instruction for initial set up, once you are done you can use some sample template or create a blank website. To know more on umbraco, Please refer below links http://our.umbraco.org/wiki/how-tos/a-complete-newbie's-guide-to-umbraco http://umbraco.com/help-and-support/video-tutorials/getting-started?freeVideos=1 http://our.umbraco.org/wiki/how-tos/getting-started-with-umbraco-what-is-next-after-you-install http://our.umbraco.org/wiki/install-and-setup ,  I have created a blank website, Now we will go step by step. Fi...

DD4TFormRouteHandler (posting a form as tridion page url)

ASP.NET routing enables us to use URLs that are not physical files, In DD4T we have the default page route definition. In which all page request redirct to Page controller and process the page. DD4TFormRouteHandler is a custom route handler responsible for mapping incoming browser requests to particular MVC controller actions, this works along with  DD4TFormHelper  (that generate the route information for the form) Posting a form in DD4T is not complicated, you can create the mvc form as a normal controller and action, then post it via AJAX. But, when we need to do post the form as normal page, It would need a tweak as the controller/action is not a page existed in tridion. This can be achieved by implementing a custom Mvc RoutHandler and reroute the posted form to the encrypted action and controller. It works as below daigram. So, how to do this. to render out the form we have BeginDD4TForm html helper as below that generate the form with encrypted route values....

Why not to have a static const in c#

This is just a thought, that I was thinking why can't we have a constant with static in C#, and the answer is 'NO'; That we cannot have a static constant; e.g: I created a class as below: public class Constants1 { public const string Const1 = "Hello"; public const string Const2 = "World"; public static string Static1 = "Hello Static"; } When we compile the program into IL, the C# compiler does a magic in IL, that the constants converts into static literals, of course it has to, that's why we are able to access the constants as Constants1.Const1