What is a Singleton Class?
In OOP, a singleton class is a class that can have only one instance or can be instantiated once at a time.
Java Singleton Pattern is one of the Gangs of Four Design patterns and comes in the Creational Design Pattern category
Why Singleton?
The primary purpose of a Single class is to restrict the limit of the number of object creations to only one. This often ensures that there is access control to resources, for example, socket or database connection.
How to create a Singleton Class?
Creating a Singleton class is super easy.
- Private constructor: We just need to declare our constructor as private, because we don’t want to instantiate objects directly from outside as it may create a new instance.
- Static factory method: Create a Static method that will return the instance as per requirement, It will check if an instance is already present or not and then return the same instance every time.
- Static member: Create a private attribute of the class type that refers to a single object.
Syntax of the Singleton Class:
class SingletonDemo { // Static variable reference of single_instance private static SingletonDemo singleObject; private SingletonDemo() { // constructor of the SingletonDemoclass } public static SingletonDemo getInstance() { // write code that allows us to create only one object // access the object as per our need } }
Types of Singleton Class :
- Early Instantiation: the creation of an instance at load time.
- Lazy Instantiation: the creation of instances when required.
Example of Singleton Class :
Code:
Java Code
class Tuf {
private static Tuf TfObject;
private Tuf() {}
public static Tuf getInstance() {
// create object if it's not already created
if (TfObject == null) {
TfObject = new Tuf();
}
// returns the singleton object
return TfObject;
}
public void GetText() {
System.out.println("Welcome To TUF.");
}
}
class Main {
public static void main(String[] args) {
Tuf t1;
// refers to the only object of TUF
t1 = Tuf.getInstance();
t1.GetText();
}
}
Output: Welcome To TUF.
The issue with Singleton Class:
Conceptually, a singleton is a kind of global variable. In general, we know that global variables should be avoided — especially if their states are mutable.
We’re not saying that we should never use singletons. However, we are saying that there might be more efficient ways to organize our code.
Bonus:
- If a singleton class is loaded by two classloaders, two instances of a singleton class will be created, one for each classloader.
- Singleton design pattern is used in core java classes also, for example, java.lang.Runtime, java.awt.Desktop.
- Singleton pattern is used for logging, driver objects, caching, and thread pool.
Special thanks to Amisha Kumari for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article