Singleton Pattern – Interview Notes (4+ Years Full Stack)
Definition
Singleton ensures that only one instance of a class exists and provides a global access point to it.
Where It Is Used
Logging systems, configuration managers, caching, and Spring Boot beans (singleton scope by
default).
Solid End-to-End Example: ConfigManager (Real Project Style)
Use case: Load application configuration once and share across services.
import [Link];
import [Link];
class ConfigManager {
private static ConfigManager instance;
private Map<String, String> config = new HashMap<>();
private ConfigManager() {
[Link]("[Link]", "localhost:3306");
[Link]("[Link]", "XYZ123");
}
public static ConfigManager getInstance() {
if (instance == null) {
instance = new ConfigManager();
}
return instance;
}
public String getConfig(String key) {
return [Link](key);
}
}
// Usage in Service 1
class UserService {
public void printDBUrl() {
ConfigManager config = [Link]();
[Link]([Link]("[Link]"));
}
}
// Usage in Service 2
class OrderService {
public void printApiKey() {
ConfigManager config = [Link]();
[Link]([Link]("[Link]"));
}
}
// Test
class Main {
public static void main(String[] args) {
ConfigManager c1 = [Link]();
ConfigManager c2 = [Link]();
[Link](c1 == c2); // true
}
}
What This Demonstrates
Only one ConfigManager instance is created and shared across multiple services. Ensures consistency
and avoids redundant object creation.
Spring Boot Context
In Spring Boot, @Service and @Component beans are singleton by default. The framework manages
lifecycle, so manual Singleton is rarely needed.
Pros
Memory efficient, centralized control, shared state.
Cons
Tight coupling, harder testing, global state risks if misused.
Interview Answer Template
Singleton ensures a single instance for shared resources like config or logging. In Spring Boot, beans
are singleton by default. However, overuse can lead to tight coupling and testing challenges.