Java Creational Design Patterns – Singleton Pattern

Singleton Pattern is one of the Creational design pattern. The singleton pattern puts restriction on object creation process; it restricts the instantiation of a class to one object. If we are using Singleton pattern, no need to instantiate class object, its the responsibility of the class to provide the way to access its one and only one object.

If your application deals with below questions then Singleton Pattern could be your solution.

  • If a class need to have only one instance
  • The class needs to be centrally accessible.
  • You need to control how the class instances are created

Singleton Pattern by Example

This pattern can be implemented in two different ways

  1. Eager initialization: In this method object of class is created when it is loaded to the memory by JVM. It is done by assigning the reference an instance directly. This approach can be used when you know that cost of object creation is not too high.
  2. Lazy initialization: In this method, object is created only when it is needed. This approach prevent resource wastage. An implementation of getInstance() method is provided which return the instance.

We will see both the ways in our coding sample.

As you can see above approach is Eager. The class instance is initialized on loading of class in JVM. Below is most popular Singleton Lazy Init

In above code you can see, a getInstance method is provided which in turn has synchronized block. This block will make sure that only one thread is doing the instance creation and rest other will use the Only available single instance.

Running the example

Running example is straight forward.

Output

Conclusion

Few people consider the singleton to be an anti-pattern in that it is frequently used in scenarios where it is not beneficial. But by far this is one of the most popular pattern being used and asked in lots of interview questions.

So basically if you –

  • Hide the constructor of the class.
  • Define a public static operation (getInstance()) that returns the sole instance of the class.

You create a Singleton Class. More over you can make your singleton class implement Cloneable , Serializable and make it clone and serialize resistant.

You can refer the code at our Github repository using link

Download Code
One Comment
  1. Peter
    August 2, 2019 | Reply

Add a Comment

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