Blog Archives

Singleton Design pattern in Java

Below class depicts the Singleton design pattern.

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

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

}

9to5Mac

Apple News & Mac Rumors Breaking All Day

Gigaom

Technology news, trends and analysis covering mobile, big data, cloud, science, energy and media

digiphile

We're already living in the future. It's just not evenly distrbuted yet.

Tech

News and reviews from the world of gadgets, gear, apps and the web

The Past and Present Future

Ken Hinckley's Ideas, Visions, and Opinions on the Research Frontiers of Human Technologies

TED Blog

The TED Blog shares interesting news about TED, TED Talks video, the TED Prize and more.

Inside BlackBerry

The Official BlackBerry Blog

Bill Mullins' Weblog - Tech Thoughts

Security and System Tools and Tips. Software Reviews, News, Views, Downloads and Links.

insanebloom

Poetry. Travel. Et cetera.