Singleton Design Pattern in Java

Singleton is one of the Gangs of Four Design patterns and comes in the Creational Design Pattern category. From the definition, it seems to be a very simple design pattern but when it comes to implementation, it comes with a lot of implementation concerns. The implementation of Singleton pattern has always been a controversial topic among developers.

Singleton is one of the most commonly used patterns. There are some instances in the application where we have to use just one instance of a particular class.

This pattern involves a single class which is responsible to creates own object while making sure that only single object get created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.

We’re going to create a SingletonExample class. SingletonExample class have its constructor as private and have a static instance of itself.

SingletonExample class provides a static and synchronized method to get its static instance to outside world. The synchronized will make sure that a single Thread can access the method in case if multi threading.

package com.javaconnect;
public class SingletonExample {
// create an object of SingleObject
private static SingletonExample instance = new SingletonExample();
// make the constructor private so that this class cannot be
// instantiated
private SingletonExample() {
}
// Get the only object available, we make this method as static and
// synchronized for Thread safe
public static synchronized SingletonExample getInstance() {
return instance;
}
public void showMessage() {
System.out.println("Hello!");
}
}