Friday, July 28, 2006
How to create Singleton
- Private static variable which holds the instance of the same class
- Private Constructor with no code in it
- Public static method that return the private static variable declared in the first step. This method should check if the variable is null, if so, create a new instance, assign it to the variable and return the variable.
class MySingleton{
private static MySingleton obj;
private MySingleton(){};
public static MySigleton GetInstance()
{
if (obj == null) obj = new MySingleton();
return obj;
}
//all other functions go here.. these functions have to be static
}
From the client, a sigleton is used like the following:
public static void main()
{
//Since MySingleton has a private constructor, it can not be instantiated like a regular class. The
following code throws an error
//MySingleton 0 = new MySingleton(); //throws errror
MySingleton obj1 = MySigleton.GetInstance(); // since this is first call, an object gets created in the GetInstance function and gets added to the class global variable of obj
obj1.function1();
obj1.function2();
//Now later when the user tried to create a new object of MySigleton, the same object is returned
MySingleton obj2 = MySigleton.GetInstance(); //returns the same object created in the first call.
}