The Singleton Pattern ensures that a class has only one instance throughout the application's lifecycle and provides a global access point to that instance. It is commonly used for shared resources such as configuration managers, logging services, caching systems, and database connection managers where multiple instances could lead to inconsistent behavior.
Key Points: • The constructor is declared private to prevent object creation from outside the class. • A single shared instance is exposed through a public static method or field. • For production systems, enum-based singleton is preferred because it is inherently thread-safe and protected against serialization and reflection issues.
Example: A ConfigurationManager stores application settings such as database URLs, API keys, and environment properties. Having multiple instances could result in inconsistent configuration data, so a Singleton ensures that all components access the same configuration object.
Code Example:
public enum ConfigurationManager {
INSTANCE;
private String environment =
"Production";
public String getEnvironment() {
return environment;
}
public void setEnvironment(
String environment) {
this.environment = environment;
}
}
public class Main {
public static void main(String[] args) {
ConfigurationManager config =
ConfigurationManager.INSTANCE;
System.out.println(
config.getEnvironment());
}
}Interview Tip: A concise interview answer is: I would implement the ConfigurationManager as a Singleton to guarantee a single shared instance across the application. The most robust approach is using an enum-based singleton because it is thread-safe by default and protects against issues caused by reflection, serialization, and cloning.