Below class depicts the Singleton design pattern.
SingletonDesignPattern.java
package in.javatutorials;
/**
* @author JavaTutorials
* @version 1.0
*
*/
public final class SingletonDesignPattern {
/**
* make the class object as private as it is
* not used directly out side the class
*/
private static SingletonDesignPattern singletonObj = null;
/**
* make the constructor as private.
* Object cannot be created using the constructor outside of this class.
*/
private SingletonDesignPattern(){
}
/**
* Create the class object if it is null and
*
* @return singletonObj SingletonDesignPattern
*/
public static SingletonDesignPattern getInstance(){
if(singletonObj == null){
singletonObj = new SingletonDesignPattern();
}
return singletonObj;
}
/**
* Take the user name as parameter and return the welcome message
*
* @param userName String
* @return message String
*/
public String getWelcomeInfo(String userName){
String message = null;
//make method access to synchronized to make thread safe
synchronized (SingletonDesignPattern.class) {
System.out.println(“User Name is : ” + userName);
message = “Hello ” + userName + “!!!”;
}
return message;
}
}
TestSingleton.java
The main() method of below class will get the single ton object and access the other methods using the same.
package in.javatutorials;
public class TestSingleton {
public static void main(String[] args) {
//Get the singleton object
SingletonDesignPattern singletonObj = SingletonDesignPattern.getInstance();
System.out.println(singletonObj.getWelcomeInfo(“Mallik”));
}
}
Enums are the new way to create singleton pattern. See a comparison of various ways to create singleton at:
Singleton design pattern in Java