Friday, July 28, 2006

 

How to create Singleton

Singleton is a 'creational pattern' which is used when 'only' one instance of the object is required for the entire client process...Singleton enforces this by creating a private/protected default constructor... here is the whole process Your singleton object should have the following:

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.

}


Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?