Singleton Design Pattern
What is a singleton design pattern?
Singleton design pattern is one of the Gang of Four design patterns. It falls under the creational design pattern. The main objective of this pattern is to ensure that a class has only instance throughout the application.
Why do we need to focus on creating a single instance?
One common use case I have come across is while using services --- whether a Backend service which interacts with a DB or a frontend service which interacts with the BE. These services could be accessed from several places throughout the app and if they don’t maintain any state, there is no need to create multiple instances of them. In such cases, a singleton comes into the picture. Many frameworks implement the services as singleton behind the scenes by using metadata. Other common use cases include logging, caching etc.
How to create a singleton pattern in java
- Instance creation - Use a private constructor. You can make the class final to avoid modifying the state via subclass(in case if the class has local state)
- Access and state - All state should be accessed within the class, so the instance should have static keyword and the access should be via a static method.
Implementating Singleton pattern
There are two ways - eager and lazy implementations of singleton.
We will look at a simple eager implementation.
In the below code both instance
and instance2
will return the same object.
import java.util.*;
public class Main {
public static void main(String[] args) {
Singleton instance = Singleton.getInstance();
Singleton instance2 = Singleton.getInstance();
System.out.println(instance); //Singleton@50de0926
System.out.println(instance2); //Singleton@50de0926
}
}
public final class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return INSTANCE;
}
}