What is the Singleton pattern?
Why Interviewers Ask This
Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid OOP Concepts basics — a prerequisite for any developer role.
Answer
The Singleton pattern ensures that a class has only ONE instance and provides a global access point to it. Classic thread-safe implementation (Java): public class DatabaseConnection { // Volatile ensures visibility across threads: private static volatile DatabaseConnection instance; private Connection connection; // Private constructor -- prevent external instantiation: private DatabaseConnection() { this.connection = DriverManager.getConnection(DB_URL); } // Thread-safe lazy initialization (double-checked locking): public static DatabaseConnection getInstance() { if (instance == null) { // First check (no lock) synchronized (DatabaseConnection.class) { if (instance == null) { // Second check (with lock) instance = new DatabaseConnection(); } } } return instance; } public Connection getConnection() { return connection; } }. Bill Pugh (enum) implementation (best for Java): public enum Singleton { INSTANCE; private final ResourcePool pool = new ResourcePool(); public void doWork() { pool.process(); } } // Usage: Singleton.INSTANCE.doWork();. Use cases: database connection pool, configuration manager, logger, thread pool, device driver management. Problems with Singleton: hard to test (can't easily mock); tightly coupled; hides dependencies; thread-safety must be carefully managed; violates Single Responsibility Principle (manages own creation + its main job). Dependency injection alternative: create one instance, inject it everywhere — testable and decoupled, without the Singleton pattern's drawbacks.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex OOP Concepts answers easy to follow.