Shahid Riaz Bhatti

if(my.work == “Interesting” || my.availableTime > my.workHours) { this.blog.Post();}

Singleton design pattern

October 22
by Shahid Riaz Bhatti 22. October 2008 17:34
IMPORTANT:  The example code which i discussed is attached at the end of this post. You can download it to compile.
 
 
  Singleton assures that there is one and only one instance of a class and provides a global point of access to it.
Why Singleton:
There are number of cases in programming when we want a class to have only one instance. e.g.
  •  Sometimes we want just a single instance of a class to exist in the system.
  • We need to have that one instance easily accessible
  • And we want to ensure that additional instances of the class can not be
    created
How to Implement Singleton pattern in C Sharp:
Ok, now we have understand that why we need the singleton, now the question is that how to implement this?
We will do two things to implement the singleton pattern which are given below:
  1. Declare a static Boolean variable to keep track that instance of the class is created or not.
  2. The constructor of the class should be private.
Now lets dig into the above two points that how these two points will be used to implement the singleton:

First we stated that we will declare a static boolean variable to keep track that the instance of the class is created or not. Secondly we stated that we will make that constructor of that class private.

This was all theory, now lets try to make our hands dirty with the code.

First of all I need to declare my class which should have the one and only one instance. Lets say I gave it the name "MySingleton". Now I will write code to accommodate my two points which I mentioned previously.
///
/// The following class will behave as singleton
///
class MySingleton
{
// The following is a static variable which
// will be used to keep the track that instance
// of this class is created or not.
private static bool IsAlreadyCreated = false;
///
/// Constructor of the class. It is declared private
/// so no one would be able to create the instance of
/// this class.
///
private MySingleton()
{
// I declared it private so now no one
// would be able to create the instance
// this class

}
///
/// It is static method. I declared it static, because
/// I have designed the class in such a way that the
/// instance of this class can not be created. And We know
/// that static method can be accessed without declaring
/// the instance of the class.
/// This method will check the static boolean variable which
/// we declared in the class. If the boolean variable is false
/// then It will return the instance of the MySingleton class.
/// Else if will return null
///
///
public static MySingleton GetSingletonHandle()
{
if (!IsAlreadyCreated)
{
IsAlreadyCreated = true;
return new MySingleton();
}
else
{
throw new MyException("Get last, I can not give you more than one handle");
}
}
}

The above code is commented and self explanatory. Now lets start write code to check our class.

In the Main program write the following line:
MySingleton _MySingleton = MySingleton.GetSingletonHandle();
if (_MySingleton != null)
{
Console.WriteLine("Instance is created");
}
else
{
Console.WriteLine("I cant not give more than one handle");
}

In the above code I am trying to get the "GetSingletonHandle()" from the MySingleton class. Here this point must be noted that the following line
MySingleton _MySingleton is just the object of the MySingleton class. It is not instantiating the instance of the class. The instance is created by using the new keyword, like this:
MySingleton _MySingleton = new MySingleton();

Ok, after getting the "GetSingletonHandle()" from the MySingleton class, I am checking that what I got (i.e. Is it null or not).
What is the meaning if I am getting null??
It means that the instance of this class was already created, and if its not null then it means that we have got the GetSingletonHandle.

Out put:
If you run program you will get the out put some thing like this:

You got the Handle

Upto this point we are almost finished with the Singleton design pattern. But I am not satisfied with the Main program which is trying to get the GetSingletonHandle(), Why?
  • Do you think that it is a good approach to always check that GetLogErrorhandle() is null or not?
If yes, then you are wrong and if no then also you are wrong. :)
If your answer is yes, then I must say that bad developers like me forgot to check these kinds of basic thing that the object on which I am going to perform some operation is null or not. So to make the life easy for the developers like me It would be good to design the singleton to throw a custom exception instead of sending null if its object is already created.

If your answer was no, then again you are wrong becasue there is no fault in the singleton class, It was my mistake that I always forgot to check the basic null checks. :)

So why not to write a small class of my own custom exception. And in the singleton class I will make use of that custom exception (i.e. if the instance was already created then throw the exception rather than throwing the null).

Ok, so here is the code of my Custome Exception class:


public class MyException: Exception
{
public SingletonException(string s) : base(s)
{
}
}

Now lets change in the GetSingletonHandle function of our Singleton class to make use of the above exception class.

public static MySingleton GetSingletonHandle()
        {
            if (!IsAlreadyCreated)
            {
                IsAlreadyCreated = true;
                return new MySingleton();
            }
            else
            {
                throw new MyException("Get last, I can not give you more than one handle");
            }
        }

}
}

Now run the program, you will get the same output. To check our complete program which we have written, we need to change our Main program, so that we can check that what happened If I asked my singleton to give me more than one handle.

My Complete program is now given below:

using System;
using System.Collections.Generic;
using System.Text;

namespace Singleton
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                MySingleton _MySingleton = MySingleton.GetSingletonHandle();
                if (_MySingleton != null)
                {
                    Console.WriteLine("Instance is created");
                }
                MySingleton _MySingleton2 = MySingleton.GetSingletonHandle();
            }
            catch (Exception ex)
            {
                
                Console.WriteLine(ex.ToString());
            }

        }
    }

    /// <summary>
    /// The following class will behave as singleton
    /// </summary>
    class MySingleton
    {
        // The following is a static variable which
        // will be used to keep the track that instance
        // of this class is created or not.
        private static bool IsAlreadyCreated = false;
        /// <summary>
        /// Constructor of the class. It is declared private
        /// so no one would be able to create the instance of
        /// this class.
        /// </summary>
        private MySingleton()
        {
            // I declared it private so now no one
            // would be able to create the instance
            // this class

        }
        /// <summary>
        /// It is static method. I declared it static, because
        /// I have designed the class in such a way that the
        /// instance of this class can not be created. And We know
        /// that static method can be accessed without declaring
        /// the instance of the class.
        /// This method will check the static boolean variable which
        /// we declared in the class. If the boolean variable is false
        /// then It will return the instance of the LogError class.
        /// Else if will return null
        /// </summary>
        /// <returns></returns>
        public static MySingleton GetSingletonHandle()
        {
            if (!IsAlreadyCreated)
            {
                IsAlreadyCreated = true;
                return new MySingleton();
            }
            else
            {
                throw new MyException("Get last, I can not give you more than one handle");
            }
        }
    }

    public class MyException : Exception
    {
        //new exception type for singleton classes
        public MyException(string s)
            : base(s)
        {
        }
    }
}




In the main program I tried to get the GetSingletonHandle() two times. first time it gave me the handle and the second time I got the exception. the screen shot of the out put is given below:




 
 
 If you are giving interview somewhere then the above explanation is good enough to show that you actually know about the singleton, but there are some issue which still needs to be covered. i.e.
 
  • What if two threads called the singleton at the same time? Well, the answer is that the two threads could create more than one instance of the class. How to overcome this issue? There are different ways to handle this issue. The first one is that make the  GetSingletonHandle() synchronized.
If you are discussing singleton with some one then they might ask you that what is Lazy instantiation and what is eager instantiation. 
The approach which we used in our singleton is called the lazy instantiation whic is "create the instance if it does not exists".
 
Eager instantiation is another apprach for implementing the singleton design pattern. In eager instantiation we create the singleton instance in a static initilizer. This is guaranted to be thread safe. So If I want to change my class to implement the eager then I will follow the following steps:
 
  •  Declare the static varible of the type singleton class (In my case it is MySingleton) and initilize it in the class. i.e.
           private static MySingleton mySingleton = new MySingleton ();
  • Now change the  GetSingletonHandle()  like this:
        public static MySingleton GetSingletonHandle()
        {
            return
mySingleton ;
        }

         
That is it. Now we have implemented the Singleton pattern using the eager instantiation.
 
You can change the singleton class according to the requirments but the bottom line is that singleton class is a class which have one and only one instance.Now its upto you that how do u ensure it in your domain and according to your requirments.
 
Regards,
Shahid riaz bhatti
Microsoft certified professional

Program.cs (2.54 kb)

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

C# | Design Patterns

RecentComments

Comment RSS

Most comments

supplynflshop supplynflshop
51 comments
tiffany-bracelets tiffany-bracelets
39 comments
AVI to iPad AVI to iPad
36 comments