✅ What is Singleton Design Pattern?
The Singleton Design Pattern is a creational design pattern that ensures only one object of a class is created throughout the application and provides a global access point to that object.
👉 In simple words:
A class using Singleton allows only one instance and prevents multiple object creation.
✅ Why Use Singleton?
Singleton is useful when exactly one object is required, such as:
- Database connection
- Logger class
- Configuration settings
- Cache manager
✅ Key Rules of Singleton Class
- Constructor must be private (to stop object creation using
new). - Create a static instance of the class.
- Provide a public static method to access the instance.
✅ Basic Singleton Example (Lazy Initialization)
class Singleton {
private static Singleton instance;
private Singleton() {
System.out.println("Object Created");
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
public class Test {
public static void main(String[] args) {
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1 == s2); // true
}
}
✔ Both references point to the same object.
✅ Types of Singleton Implementation
1️⃣ Eager Initialization
Object created at class loading time.
private static Singleton instance = new Singleton();
2️⃣ Lazy Initialization
Object created only when needed.
3️⃣ Thread-Safe Singleton
Used in multithreading environments.
public static synchronized Singleton getInstance() {
if(instance == null)
instance = new Singleton();
return instance;
}
4️⃣ Bill Pugh Singleton (Best Practice)
Uses static inner class — efficient and thread-safe.
✅ Advantages
- Saves memory
- Controlled access to resources
- Global access point
- Prevents multiple object creation
Join the No 1 Java Real Time Projects Online Training in 2026 and gain practical exposure with live coding sessions, real-world case studies, and expert guidance.
Top comments (0)