💡 Problem:
How do we ensure that a class has only ONE instance throughout the application?
💡 Common Use Cases:
- Logger
- Configuration Manager
- Database Connection
💡 Approach:
We restrict object creation and provide a global access point.
💡 Key Idea:
- Private constructor
- Static instance
- Public method to access it
💻 Java Example:
java public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
⚠️ Insight:
This version is NOT thread-safe. In multithreaded systems, we need synchronization or double-check locking.
📌 Takeaway:
Singleton is simple but tricky in real-world scenarios.
Top comments (0)