Singleton Design Pattern Java
By AmarSivas | | Updated : 2021-09-28 | Viewed : 250 times

Singleton is used widely in programming languages such as java. So We will learn here when to use and how to implement singleton class in java.
Table of Contents:
What is Singleton?
Singleton with Eager Initialization
In the Eager initialization, the object will be created after loading the class. Please notice the below given example.
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {
System.out.println("Singleton object creation...");
}
public static Singleton getInstance() {
return instance;
}
}
The Eager initialization has one drawback. Even though Singleton objects are not useful in some applications the Eager initialization of Singleton will simply create objects.
Singleton with Static Block Initialization
It is also similar to Eager initialization of the Singleton. The difference is the object is instantiated in a static block.
public class Singleton {
private static final Singleton instance;
static {
instance = new Singleton();
}
private Singleton() {
System.out.println("Singleton object creation...");
}
public static Singleton getInstance() {
return instance;
}
}
Singleton with Lazy Initialization
To overcome the problem of Eager initialization of Singleton The lazy initialization came into the picture. We will look into this how it will be working.
public class Singleton {
private static Singleton instance;
private Singleton() {
System.out.println("Singleton object creation...");
}
public static Singleton getInstance() {
if (instance == null)
instance = new Singleton();
return instance;
}
}
In the Multithreading scenario, the above-given code will fail. It may create more than one object. So the above-given code has to be dealt with for Multithreading. And there are more cases to deal with. We will discuss that in further sections.