Search This Blog

Loading...

Nov 28, 2011

How to Implement Singleton Pattern in C Sharp


Sponsored Links:

Design patterns are the solution of problem those comes regularly in software engineering, It speed up the development process by providing proven and tested solutions in the form of different prototype. In simple word we can say design patterns are the template for solving any issue.
It tell you the way so that you can easily solve the problem. There are lot's of patterns are existed in today's world. Singleton is one of the best pattern. Each pattern are specific to the particular problem. You can implement pattern as per your requirement.  Be careful before choosing any pattern.

"Singleton pattern" is one of the best patterns of software engineering and it is very easy to understand and execute. Performance wise it is fast because it loads everything in a one go.

Purpose: When you have the requirement to define the global access point to your object then singleton pattern is come into picture. In those situations you can implement singleton pattern.
A singleton pattern ensures that the class has only one instance and classes are responsible to creating their instances. When class is loaded first time, instance will also loaded, in subsequent calls the same object of class will be used that you can check by locking mechanisms.

In Csharp you can create singleton pattern by creating private constructor


private testSingleton() ;   and a

static instance variable of same class
private static testSingleton _objTestingSigletion;  

Where  testSingleton() is your class name.

Sample Code :

public sealed class testSingleton
{
private static int  _instanceOccurance;
private static  testSingleton _objTestingSigletion = new testSingleton();


private testSingleton()
{
_instanceOccurance = 1;
}

public static testSingleton GetInstance()
{
if (_objTestingSigletion == null)
{
 // Lazy initialization
_objTestingSigletion = new testSingleton();
}
_instanceOccurance++;
return _objTestingSigletion;
}

public static int Reference
{
get { return _instanceOccurance; }
}


}
Above code has only one limitation, consider a situation where your two instances are running at the same time then both instances get created which are not the singleton concepts.  However Singleton pattern says “You can create only one instance during the entire life cycle”.

Related Article
Thread safe singleton pattern in C Sharp 

Follow by Email