Singleton class example program

A singleton class having a single object or Instance of a class for entire lifetime of the application. Singleton class restricts the instantiation of a class to one object.
Example:  java.lang.Runtime which provides getRuntime() to have the instance of class.
 You want to have just one Database connection in the whole application
Steps to create Singleton class:
1.Create a class with name SingletonExample.
class SingletonExample
{
}
2.Declare a private static variable to hold single instance of class.
private static SingletonExample singletonref=null;
3.Declare a default private constructor.so that other classes cant create object for this class
Private SingletonExample() { };

4.Declare a public static synchronized function that returns the single instance of class, When we use our singleton in a multi threaded application we need to make sure that instance creation process not resulting more that one instance, so we add a synchronized keywords to protect more than one thread access this method at the same time.
public static synchronized Singleton getInstance()
{

if(singletonref == null)
{
singletonref = new SingletonExample(); //returns new object, if object is null.

}
return INSTANCE; // otherwise return object
}
5.It is also advisable to override the clone() method of the java.lang.Object class and throw CloneNotSupportedException so that another instance cannot be created by cloning the singleton object.
protected Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException("Clone is not allowed.");
}

Here is the Example:

class SingletonExample {
// Make all constructors private

private SingletonExample() {}

// Declare a private static variable to hold single instance of class

private static SingletonExample singletonref = null;

// Declare a public static function that returns the single instance of class

public static SingletonExample getInstance() {

// Do "lazy initialization" in the accessor function.

if(singletonref == null) {

singletonref = new SingletonExample();
}
return singletonref;
}
}
public class MySingletonClassObject
{
public static void main(String[] args)
{
System.out.println("Singleton Test!");
// always return the same instance

System.out.println("SingletonExample instance id :"+SingletonExample.getInstance());

System.out.println("SingletonExample instance id :"+SingletonExample.getInstance());

System.out.println("SingletonExample instance id :"+SingletonExample.getInstance());

// can't create instance of Singleton class

//SingletonExample instance2 = new SingletonExample(); // Compilation Error
}
}

Search This Blog

All the rights are reserved to this blog is belongs to me only.. Powered by Blogger.