Singleton Design pattern in JAVA

Posted: January 5, 2013 in Java Posts
Tags: , , , , ,

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

}

Advertisements
Comments
  1. Taha Iqbal says:

    Assalam walaikum, I have been following your blog. I want to request you about sharing your server setting up experience. Here are few of the problems I am having right now (these might be beginners problem), here are they – Setting up Tomcat 6/7 Server on Linux Cent OS. – Security concern, either to make tomcat primary server (which listens directly to port 80) , or setting up tomcat while redirecting all the request to port 8080 via ip tables(request forwarding). – Advantages of setting Apache as front server. – Hosting multiple domains under single Tomcat.

    If you can write to some or all of these topics , it will be helpful. Taha Iqbal

    Date: Sat, 5 Jan 2013 06:51:26 +0000 To: tahaiqbalkhan9@hotmail.com

    Like

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s