Singleton Pattern

Tharaka Dissanayake
3 min readJun 29, 2022

Singleton Pattern is used to create a single instance for a container if it is Java, only one instance for JVM. (You can go with the factory pattern if you take arguments to create an instance.) Mainly this pattern is used to handle database operations. Usually, one database instance should be for one application.

Edge cases

🔹Hard to unit test.

The creation of the singleton object can not be controlled because it is often created in a static initializer or method. Therefore, the developer can’t mock out the behaviour of that Singleton instance.

🔹The thread-safety code must be considered before implementing the singleton pattern.

Steps for implementing the singleton pattern

· You must need to privatize the constructor. Therefore, anyone can not create an instance of this singleton class.

· You need to create a static variable to store the instance of this singleton class. It must be static because you can not create an instance of this class in another class.

· You need to provide(return) the created instance of the singleton class.

Example

1-Create the “Manager” class with a private constructor.

2- Create the private static field to hold the class instance (instance).

3- Create a static method to get the created instance.

Manager class diagram
Manager (Singleton) class
Main class
Result

The exact address for two objects is received. It means there is only one object in the heap.

Thread-safe code for the Singleton pattern. (Double-checking method)

Sometimes there may not be created object of the Manager class. So first, we need to check whether there is a manager object. If it is not, we must create an object.

Suppose there are two or multiple threads in operation. It is possible to create multiple objects. So, we need to develop thread-safe code to avoid creating multiple objects.

Thread-safe manager (singleton) class

--

--