Singleton in .net
There are some instances when we need only single object of class. For example MDI form is always has single object. For this we need to restrict class to create multiple objects. For this we can use private constructor. Class having private constructor cannot instantiate. In other word, we cannot create object of class.
The declaration of empty constructor is prevents the declaration of default constructor. If you are not giving any access modifier of with the constructor its by default private.
Now how you stop creating more than one object of class. With the help of private constructor you can achieve this functionality.
public class SingletonClass
{
int i;
static SingletonClass objSingletonClass;
private SingletonClass()
{
i = 10;
}
public static SingletonClass getInstance()
{
if (objSingletonClass == null)
{
objSingletonClass = new SingletonClass();
}
return objSingletonClass;
}
public int getValue()
{
return i;
}
}
In this code, I am creating private constructor of class. Now problem is that how I create instance of class if I had created private constructor. To solve this problem I had create static method getInstance(). In this method I am returning instance of static class object. The pattern I am using for creating object is singleton.
Singleton pattern ensures a class has only single instance, and provide a global point of access to it.
| Download Singleton Code |
| Date:- 2 July, 2009 |