Design Pattern For Beginners - Part-1: Singleton Design Pattern

Today let’s start with very common and easy design pattern called Singleton design pattern.

Welcome to the Design Pattern For Beginners article series. Here in a few parts I will be discussing various design patterns (in other words a few of the most popular) basically targeting beginners. Most of the patterns I will discuss in my own style and my own words. And before starting any pattern, we will try to find the basic need for it. So, let's start our journey with a very nice quote.

"It's easy to walk on water and develop software from specifications, when both are frozen."

Hey, that's not mine!! And I have forgotten from where I read it. My poor memory says I read it somewhere in someone's blog. If anyone has any information please put a few keystrokes in the comments section.

Anyway, let's return to the subject of this article. Really, it's very easy to develop software from specifications and when the requirements are constant. But by nature people are not happy with constant and fixed needs. (Yes that's why language designers created variables! Ha... Ha...)

And here design patterns come in to play. If we implement a proper design pattern then we need not worry much when new requirements are added to the old ones. And here lies the importance of design patterns.

As I said earlier, this article series is targeted to young developers and if you fall in this category then this introduction is enough to make explain "Why a design pattern is very essential".

I am grateful to "Shivaprasad koirala Sir"; yes, from your video tutorial I have heard the word "Design pattern" for the first time and many many thanks for providing the first gear of my design pattern journey.

Ok, that's a long introduction. Today let's start with a very common and easy design pattern called "Singleton Design Pattern".

Singleton Design Pattern 

Let's learn why the Singleton Design Pattern is implemented. And then we will see how to implement it in C#.

Basic need: Think, there is a hit counter in any web application. (Yes I know you have already seen many examples like this). Now, by nature when a visitor hits a web application it will increase by one. This is one scenario where we can implement the Singleton Design Pattern.

Or think about another situation where you want to share a single instance of a class across various threads.

Basically we can implement the singleton pattern in one of two ways.

1. Make the constructor private so that no one can create an object of the singleton class

Have a look at the following code to understand the basic concept.

  1. using System;  
  2. using System.Collections;  
  3. using System.Data.SqlClient;  
  4. namespace Test1  
  5. {  
  6.     class singleTon  
  7.     {  
  8.         public static int counter = 0;  
  9.         private singleTon()  
  10.         {  
  11.             //Private constructor will not allow create instance  
  12.         }  
  13.         public static int Returncount()  
  14.         {  
  15.             return counter;  
  16.         }  
  17.         public static void IncreaseCount()  
  18.         {  
  19.             counter++;  
  20.         }  
  21.     }  
  22.     class Program  
  23.     {  
  24.         static void Main(string[] args)  
  25.         {  
  26.             //singletone design pattern  
  27.             Console.WriteLine("Before increase : " + singleTon.counter);  
  28.             singleTon.IncreaseCount();  
  29.             Console.WriteLine("After Increase:" + singleTon.counter);  
  30.             Console.ReadLine();  
  31.         }  
  32.     }  

Here is some sample output:


 
Ok, you may thinking, Sourav!! We are not creating any object at all in the above example but in the introduction why did you say that we will create a single object and share it across threads.  Yes we will get to that in the next example but believe me it's also a design style of a singleton pattern. Ultimately we are sharing a single class across various threads (though here we did not implement any multi-threading concept). Oh! Are you worried about deadlock problems? Ok let's see the next example.

2. Create single instance and share across threads

In this example we will implement a singleton class in such a way that only one instance of that class is possible and if the second request comes then it will return the previously created object only. Have a look at the following code.

  1. using System;  
  2. using System.Collections;  
  3. using System.Data.SqlClient;  
  4. namespace Test1  
  5. {  
  6.     public sealed class singleTon  
  7.     {  
  8.         public Int32 Data = 0;  
  9.         private static singleTon instance;  
  10.         private static object syncRoot = new Object(); //For locking mechanism  
  11.         private singleTon() { } //Private constructor  
  12.         public static singleTon Instance //Property  
  13.         {  
  14.             get  
  15.             {  
  16.                 if (instance == null)  
  17.                 {  
  18.                     lock (syncRoot)  
  19.                     {  
  20.                         if (instance == null)  
  21.                             instance = new singleTon();  
  22.                     }  
  23.                 }  
  24.                 return instance;  
  25.             }  
  26.         }  
  27.     }  
  28.     class Program  
  29.     {  
  30.         static void Main(string[] args)  
  31.         {  
  32.             //singletone design pattern  
  33.             singleTon s = singleTon.Instance;  
  34.             s.Data = 100;  
  35.             Console.WriteLine("Data of S object : " + s.Data);  
  36.             singleTon s1 = singleTon.Instance;  
  37.             Console.WriteLine("Data of S1 object : " + s.Data);  
  38.             Console.ReadLine();  
  39.         }  
  40.     }  
  41. }
Here we have defined a member called instance within the singleton class. And within the class property (yes it's also Instance, but don't be confused) we are checking whether instance is null using a condition in an if starement. If it is null then no instance is created of this class and if it is not null then an instance has already been created and it's time to return the previously created instance.

Here is sample output of this example.



Now, we will analyze the Main() function here. Have a look at the following code: 
  1. singleTon s = singleTon.Instance;  //First instance  
  2. s.Data = 100; //Data of first instance           
  3. Console.WriteLine("Data of S object : " + s.Data);  
  4. singleTon s1 = singleTon.Instance;  //Again request and return old instance  
  5. Console.WriteLine("Data of S1 object : " + s.Data);  //Show data of old instance  
  6. Console.ReadLine();
In the first two lines we are creating the first instance of the singleton class and set the data value. Now in the fourth line we are again requesting a new object of the singleton class but there is no chance to get a new one (siince this is our main target) and from the property the old one is returned. Yes that's why in the fist object we have set Data=100 and it has been reflected in the second instance, hence prooving that no new object has been created.

Conclusion

It's time to summarize my article. By habit in my previous "Best performance of C# code" series of articles I wrote something for my dear respected Sam (Who is a really enthusiastic editor and critic of C# article). Sam waiting for your comment and let's improve my way of learning. Make me more serious before writing the next sample of code for my next article.