Singleton Pattern in Java

Implementing a Singleton Class Pattern in Java is a common and easy task. The Singleton Pattern (as definied by the Gang of Four in 1995) is to “ensure a class only has one instance, and provide a global point of access to it.”

The idea behind the Singleton pattern is that there can only be one unique object of the class in existence at any one time. To make this possible we must make the constructor private and instead create a public getInstance() method that controls access to the constructor, returning a new object if none exists or returning the already instantiated object if one does. We must also override the clone() method from the Object superclass as this oft forgotten method will provide a workaround to our Singleton protection.

Here we have an example of the simplest possible Singleton class which I call, Singleton. It has only those methods absolutely necessary for the pattern and one console print statement in the constructor so that we can easily see when the constructor is called.

Singleton.java

public class Singleton {
     private static Singleton instance;
     private Singleton() {
          System.out.println("Singleton Constructor Called");
     }
     public static synchronized Singleton getInstance() {
          if (instance == null)
               instance = new Singleton();
          return instance;
     }
     public Object clone() throws CloneNotSupportedException {
          throw new CloneNotSupportedException();
     }
}

Now that we have a working Singleton class we need to make a simple test harness to see how we can call it and how it behaves. In our test we will simply create two objects, mySingleton and myOtherSingleton and we will see when the constructor method is called.

TestSingleton.java

public class TestSingleton {
        public static void main (String[] args) {
                System.out.print("Calling First Instance: ");
                Singleton mySingleton = Singleton.getInstance();
                System.out.print("Attempting to Call Again: ");
                Singleton myOtherSingleton = Singleton.getInstance();
        }
}

Hopefully this will help you write quick and easy Singleton pattern classes in the future.

See also: Sheep Guarding Llama Singleton Pattern in C#

Leave a comment