Singleton Design pattern in JAVA


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”));
}

}

What is a singleton class?How do you writer it? Tell examples?


A class which must create only one object (ie. One instance) irrespective of any number of object creations based on that class.

Steps to develop single ton class:-

1.Create a Private construcor, so that outside class can not access this constructor. And declare a private static reference of same class

2.Write a public Factory method which creates an object. Assign this object to private static Reference and return the object

Sample Code:-

class SingleTon

{

private static SingleTon st=null;

private SingleTon()

{

System.out.println(“\nIn constructor”);

}

public static SingleTon stfactory()

{

if(st==null) st=new SingleTon();

return st;

}

}

 

 

For complete Example of Singleton design pattern click here