Friday, December 23, 2011

How To Implement a Singleton class in java?

Singleton class: Singleton is a class which has only one instance throughout the application. So that it does not allow to create more than one instance.

How to implement singleton class:
Creating and implementing a singleton class is very simple. To implement singleton class, first we make the constructor as private. So that we can not create an object outside the class. We declare an object as static. Later we create one static method. So that before creating an object, we can call this method by using class name. In this method we create an object of a class.Consider the follwoing example that illustrates how to create a singleton class.

Example:
class singletonexample
{
private static singletonexample obj;
private singletonexample()
{
}
public static example()
{
if(obj==null) //it will be true only if the object is not created before
obj=new singletonexample();
}
}

class demo
{
public static void main(String args[])
{
singletonexample.example(); //with class name we call static method
}
}

   In the above example, constructor is declared as private. So that we can not create an object outside the class. We declared one static method. So that we can call this method before creating an object of a class. If(obj==null) , it verifies whether the object is already created or not. If the object is not created before, it will return true.