Wednesday, February 20, 2008

Singleton Design pattern

This is my first blog in a series of blog which I am planning to write on design patterns. The reason why I am planning to write blog on design pattern is that in the interviews I conduct 99% people are not aware of design patterns. To start with I will blog on singleton design pattern. Singleton is one of the simplest design pattern and it is very easy to implement. It falls under the creational pattern of the Gang Of Four’s (GOF) design pattern. First lets see what is singleton design pattern.


What is singleton design pattern?
Singleton design pattern is one which says that at any point there should be only one instance of the class present through out the lifecycle of the application. In other words the singleton class should take care that there should not be more than one instance of the class in memory till the application is alive. So how can I achieve this? To know read on.....

Pattern were developed to solve a set of problem and the problem singleton solves is there should exists only one instance of a class and the principle to solve the problem are as follows.

1. Declare the class constructor private
2. Once constructor is declared private then one cannot create the instance of the class, so how to create an instance? Expose a static method which creates an instance of the same class.
3. Have a class level static variable which is of the same type as that of the singleton class itself.

Now we have the principles behind the singleton, lets see how we can achieve this programmatically.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Singleton
{
#region Singleton
public class Singleton
{
///


/// The static variable of the class which will hold the instance of the class.
///

private static Singleton singleInstance;
private static int counter;
///
/// Private constructor which will restrict the direct instance creation.
///

private Singleton()
{
counter++;
}
///
/// The static method which will take care of creation of only instance of class by checking
/// the static variable for not null.
///

///
public static Singleton CreateInstance()
{
if (singleInstance == null)
{
singleInstance = new Singleton();
}
return singleInstance;
}

public void PrintInstanceCount()
{
Console.WriteLine(counter);
Console.ReadLine();
}
}
#endregion

class Program
{
static void Main(string[] args)
{
Singleton s1 = Singleton.CreateInstance();
Singleton s2 = Singleton.CreateInstance();
Singleton s3 = Singleton.CreateInstance();
Singleton s4 = Singleton.CreateInstance();
Singleton s5 = Singleton.CreateInstance();
Singleton s6 = Singleton.CreateInstance();
s1.PrintInstanceCount();
s2.PrintInstanceCount();
s3.PrintInstanceCount();
s4.PrintInstanceCount();
s5.PrintInstanceCount();
s6.PrintInstanceCount();
}
}
}

From the above code one can infer that we have a class called “Singleton” which implements singleton design pattern. It has got a private constructor which will prevent the direct creation of the class. Then we have static variable called “singleInstance” which will hold the instance of the “Singleton” class. And finally we have a static method called “CreateInstance” which takes care of creating the class. So at any given point of time if you want to create an instance of the class you do it by calling the static method "CreateInstance". Inside the method we have a "if" checking which checks whether the static variable (singleInstance) is null, if it is, then the method creates a new instance of the class assigns the new object to the "singleInstance" static variable and returns it else it returns the same object which is already created and assigned in the static variable, singleInstance.

So from above explanation it would have been clear on how to implement singleton design pattern. The method "CreateInstance" in conjunction with the private constructor and static variable makes sure that at any given point there exits only one instance of the class in memory.

12 comments:

  1. I have studied your blog given by my friend, really very simple and easy to understand. Thank you very much. Please write the blogs for all the design patterns with samples will be very helpful for guys like me.

    ReplyDelete
  2. Hey Nice innovative work you have done.So I have spread this link to my friends also. KS has commented above after tasting this.

    Antony Joeson

    ReplyDelete
  3. Irs really good and simple to understand, please post articles like this.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Hi Sandeep,
    the above article is really interesting and useful for the freshers too sir,...

    ReplyDelete
  6. Hi Sandeep,
    Excellent Article..Can you please tell me any real time scenario where can i use it?

    Thanks in Advance,
    Senthil.D

    ReplyDelete
  7. Hi,
    The real life scenario would be when you have some application level configurations. These configurations can be loaded as a singleton object b'coz configuration don't call creation of multiple objects.

    ReplyDelete
  8. Hi,
    Thanks for the response.I am the big fan of your articles.Pls do write some articles on WCF also.

    Many thanks,
    Senthil.D

    ReplyDelete
  9. Hi Sandeep,

    This is really good article. This is done helpful to understand & implement by your post.

    ReplyDelete
  10. I have implemented the above pattern.
    But I have come up with some confusion...
    Can you please make me clear...
    My question is I have created two classes called CalculateInterest.cs and CalculateDividend.cs in class liabraries.
    Both classes are public.
    In CalculateInterest class I have defined one public method called CalculateInterestForCurrentYear which will return me the integer value;
    but to access that method I have to call the createInstatnce method explicitely,
    because in this class I have implemented singleton pattern.
    And in CalculateDividend class I have defined one method called CalculateDividentForCurrentYear which is defined as static, but my class is public.
    And to access that method I dont have to create any instance of the class.
    So I want to know that which one is better should follow the singleton pattern or the other way.
    Please tell me If 10 people are accessing the
    CalculateDividendForCurrentYear static method from public class CalculateDividend then How many objects will be created and how memory allocation will be allocated.

    ReplyDelete
  11. I have implemented the above pattern.

    But I have come up with some confusion...

    Can you please make me clear...

    My question is I have created two classes called CalculateInterest.cs and CalculateDividend.cs in class liabraries.

    Both classes are public.

    In CalculateInterest class I have defined one public method called CalculateInterestForCurrentYear which will return me the integer value;
    but to access that method I have to call the createInstatnce method explicitely,
    because in this class I have implemented singleton pattern.

    And in CalculateDividend class I have defined one method called CalculateDividentForCurrentYear which is defined as static, but my class is public.

    And to access that method I dont have to create any instance of the class.

    So I want to know that which one is better should follow the singleton pattern or the other way.

    Please tell me If 10 people are accessing the
    CalculateDividendForCurrentYear static method from public class CalculateDividend then How many objects will be created and how memory allocation will be allocated.

    ReplyDelete
  12. Hi,
    You are confusing totally two different things. Singleton is a design pattern where you make sure that only one object is present throughout the life of the application.
    Whereas static is a language feature. You can define any type as static and it will be there till the application domain is alive.
    Now regarding how many objects will be created for a static method. The answer is no objects will be created unless and until you create an object for the class which has a static method. Just by accessing static method no instance of the class gets created. Only the local variable of the static method will be created.

    ReplyDelete

Leave your valuable comments here.