What is the Singleton pattern and how do you implement it?
Singleton ensures a class has exactly one instance and gives a global access point to it. Make the constructor private, keep the instance in a static field, and return it from a static method.
Explain it simply
A college has exactly one principal's office. Everybody who needs the principal goes to the same office; nobody builds a second one. A Singleton makes sure only one object exists, for things such as application configuration or a logger.
Example
class AppConfig {
private static final AppConfig INSTANCE = new AppConfig(); // created once
private final String appName = "AI Tapri";
private AppConfig() { } // nobody else can call new
static AppConfig getInstance() { return INSTANCE; }
String name() { return appName; }
}
AppConfig a = AppConfig.getInstance();
AppConfig b = AppConfig.getInstance();
System.out.println(a == b); // prints: trueSteps: private constructor, private static instance, public static getter. In Python, a module-level object does the same job, because a module is loaded only once and then shared.
What to say in the interview
"Singleton guarantees a single instance with a global access point: private constructor, a static instance and a static getter. It suits shared resources such as configuration, but I use it sparingly because of the global state it introduces."
Common mistakes
- Making the constructor public, so anyone can still create more instances.