Singleton Class
The Class which allows only to create a single object is known as singleton class in java. First time it will create an object and second time onward it will return the same object which is created earlier. This class object can be created only through a factory method, because it's constructor is private.
Example
package com.els.core;
import java.io.Serializable;
public class SingleObject implements Cloneable, Serializable
{
//create an object of SingleObject
private static SingleObject instance =null;
//make the constructor private so that this class cannot be instantiated
private SingleObject()
{
//arguments
System.out.println("Singleton object created...");
}
//Get the only object available
public static SingleObject getInstance() throws Exception
{
if(instance==null)
{
instance= new SingleObject();
}
return instance;
}
//non static method
public void showMessage()
{
System.out.println("Singleton Class!");
}
}
******
package com.els.core;
//creating object of singleton class
public class SingleTest
{
public static void main(String[] args)
{
try{
//first time creating object
SingleObject obj1 = SingleObject.getInstance();
//second time
SingleObject obj2 = SingleObject.getInstance();
System.out.println(obj1);
System.out.println(obj2);
obj1.showMessage();
}catch(Exception e){
e.printStackTrace();
}
}
}
Compile both class and execute.
javac SingleObject
javac SingleTest
java com.els.core.SingleTest
Output
Singleton object created...
com.els.core.SingleObject@f9f9d8
com.els.core.SingleObject@f9f9d8
Singleton Class!
Note : But the above class is not fully singleton class. We will discuss on next topic. Please share your feedback as comment.