The Singleton Pattern is a creational design pattern that ensures a class has only one instance and provides a global point of access to it. It's commonly used when exactly one object needs to coordinate actions across a system, such as managing database connections or configuration settings.
Key Concepts 🔍
- Lazy Initialization: Creates the instance only when needed
- Eager Initialization: Initializes the instance at startup
- Thread Safety: Requires careful handling in multi-threaded environments
- Static Factory Method: Often used to implement the pattern
Implementation Examples 📜
// Eager Initialization
public class EagerSingleton {
private static final EagerSingleton instance = new EagerSingleton();
private EagerSingleton() {}
public static EagerSingleton getInstance() {
return instance;
}
}
// Lazy Initialization with Double-Check Locking
public class LazySingleton {
private static volatile LazySingleton instance;
private LazySingleton() {}
public static LazySingleton getInstance() {
if (instance == null) {
synchronized (LazySingleton.class) {
if (instance == null) {
instance = new LazySingleton();
}
}
}
return instance;
}
}
Common Use Cases 📈
- Database Connection Pool
- Configuration Manager
- Logging Systems
- Session Management
Pros & Cons ⚖️
✅ Advantages:
- Centralized control of resources
- Avoids redundant object creation
❌ Disadvantages:
- Can make testing difficult
- Violates the Single Responsibility Principle in some cases
Further Reading 📚
For a deeper dive into other design patterns, check out:
/[[en/videos/advanced/java/oop/design_patterns/factory]]