Skip to main content

What is the Singleton pattern?

Singleton is a creational design pattern that guarantees a program has only one instance of a given class and provides a global access point to it.

The core idea

Some objects logically must exist as a single instance: for example, an application configuration, a logger, a database connection pool, a system cache. The Singleton pattern controls object creation so that the program cannot create more than one copy of the class.


Key traits

  1. Private constructor - so no one can create the object directly with new.
  2. Static field - stores the single instance of the class.
  3. Public static method - returns that instance (or creates it on first access).

Example (in Java)

java
public class Singleton { private static Singleton instance; // the single instance private Singleton() {} // private constructor public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); // lazy creation } return instance; } }

Thread-safe version

In a multithreaded environment, two threads can end up creating an instance at the same time. Solutions:

  • Use synchronized on the getInstance() method.
  • Or apply Double Checked Locking:
java
public class Singleton { private static volatile Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) instance = new Singleton(); } } return instance; } }
  • Or use initialization through a static block (Eager initialization) - the instance is created immediately when the class is loaded:
java
public class Singleton { private static final Singleton instance = new Singleton(); private Singleton() {} public static Singleton getInstance() { return instance; } }

Advantages

  • Controls the number of instances.
  • Global access point.
  • Saves resources (if creation is expensive).

Disadvantages

  • Hard to test (global state).
  • Violates the single responsibility principle (the class manages its own lifecycle).
  • Can cause hidden dependencies between components.
  • Requires synchronization in a multithreaded environment.

When to use it

  • When you need a single object to manage a shared resource (for example, logging, cache, configuration).
  • When you need centralized access to state.

Analogy

Imagine a city has one mayor. He handles every matter, and citizens have no way to create a second one. That is the essence of Singleton - a single controlling object in the system.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.