About these ads

Archive

Posts Tagged ‘how to write singleton design pattern in java’

Singleton Design pattern in JAVA

December 30, 2012 4 comments

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

}

About these ads

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

April 16, 2010 Leave a comment

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

Follow

Get every new post delivered to your Inbox.

Join 319 other followers