Create a Singleton class in Java

In this post, you will learn to create a Singleton class in Java. Let’s first see what Singleton class is.

What is a Singleton class in Java?

A Singleton class in Java is a class that can have only one object at a time. Singleton’s purpose is to control object creation. We can ensure that only one object of a class can be created by implementing the Singleton pattern.

Singletons often control access to some resources. If for example, we are being charged for each connection to some cloud database, using the Singleton class, we can ensure that only one connection is being created and that will be used in all requests to the database.

To create a Singleton class, we need to:

  • Create a private constructor to ensure that the class can not be instantiated
  • Write a static method that returns the object of the Singleton class

Create a Singleton class in Java

In this example, we follow the rules of the Singleton pattern. We add a private constructor, a static field that holds the object, and one static method getInstance(), that returns the created object.

Example

class SingletonClass {

  // static field that holds an instance
  private static SingletonClass instance;

  public String word;

  // private constructor
  private SingletonClass() {
  }

  // static method that creates an instance of the Singleton class
  public static SingletonClass getInstance() {
    // To ensure only one instance is created
    if (instance == null) {
      instance = new SingletonClass();
    }
    return instance;
  }
}


With the above, if we call the getInstance() method multiple times, we will get the same instance each time.

Example

class Test {

  public static void main(String[] args) {
    SingletonClass sc1 = SingletonClass.getInstance();
    SingletonClass sc2 = SingletonClass.getInstance(); // sc2 points to the same object as sc1
    SingletonClass sc3 = SingletonClass.getInstance(); // s1, sc2 and sc3 point to the same object

    sc1.word = "hello1";

    System.out.println("sc1 word: " + sc1.word);
    System.out.println("sc2 word " + sc2.word);
    System.out.println("sc3 word: " + sc3.word);
    System.out.println();

    // changing the value of the string for the sc3. It will reflected to sc1 and sc2 also
    sc3.word = "hello3";

    System.out.println("sc1 word " + sc1.word);
    System.out.println("sc2 word: " + sc2.word);
    System.out.println("sc3 word: " + sc3.word); 
  }
}
Output: sc1 word: hello1 sc2 word hello1 sc3 word: hello1 sc1 word hello3 sc2 word: hello3 sc3 word: hello3
 
Here, when we call the getInstance() static method for the first time, it will create an object of a class and assign it to the “instance” static field. 
 
Next time when we call the getInstance() method, the same object will be returned, and there will be no new object creation.
 
That’s it!

Leave a Reply

Your email address will not be published. Required fields are marked *