Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 57 ยท Creational Patterns

Singleton

Learn the Singleton design pattern: lazy and eager creation, thread safety in Java and C++, module singletons, and why it often hurts testing.

The Singleton pattern ensures that a class has exactly one instance and gives everyone a global point of access to it. It is the most famous design pattern and also the most misused. Its intent is reasonable: some things should exist once per program, such as a configuration object, a logger or a connection manager. Its price is also real: hidden global state, tangled dependencies and tests that affect each other.

In this lesson you will build singletons in JavaScript, see how Java and C++ make them thread safe, learn why Python and JavaScript modules are already singletons, and then see why many experienced developers prefer to avoid the pattern and use dependency injection instead.

The intent

Exactly one No second instance can be created.
Global access Any code can ask for it.
Controlled creation The class decides when it is built.
1 / 2

Structure and the two creation styles

A classic singleton has three parts: a private constructor so nobody else can create instances, a static field to hold the single instance, and a static accessor, usually called getInstance().

There are two timing choices:

  • Eager initialization creates the instance when the class is loaded. It is simple and naturally thread safe, but it does the work even if the object is never used, and any failure happens at startup.
  • Lazy initialization creates the instance the first time getInstance() is called. It saves work when the object is rarely needed, but needs care in multi-threaded code, because two threads could both see "no instance yet" and each build one.

JavaScript has no real private constructors for this purpose, so the usual trick is a module-level variable plus a guard. Below is a lazy singleton and a quick proof that every caller gets the same object.

JS A lazy singleton in JavaScript

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The "creating" message prints only once, which shows laziness: nothing existed until the first call. JavaScript runs your code on a single thread, so you do not face the race described next, unless you use Web Workers, which have separate memory anyway.

Thread safety in Java and C++

In languages with real threads, lazy creation needs protection. This naive Java version has a race: two threads can both pass the null check.

Java
// BROKEN under concurrency
class Registry {
    private static Registry instance;
    private Registry() {}
    public static Registry getInstance() {
        if (instance == null) {
            instance = new Registry();   // two threads may both get here
        }
        return instance;
    }
}

Safe options in Java:

Java
// 1. Eager: the JVM guarantees class initialization happens once.
class EagerRegistry {
    private static final EagerRegistry INSTANCE = new EagerRegistry();
    private EagerRegistry() {}
    public static EagerRegistry getInstance() { return INSTANCE; }
}

// 2. Lazy holder idiom: the inner class loads on first use.
class HolderRegistry {
    private HolderRegistry() {}
    private static class Holder {
        static final HolderRegistry INSTANCE = new HolderRegistry();
    }
    public static HolderRegistry getInstance() { return Holder.INSTANCE; }
}

// 3. Enum: concise, and also safe against serialization and reflection tricks.
enum EnumRegistry {
    INSTANCE;
    public void doWork() { /* ... */ }
}

The enum form is the one Joshua Bloch recommends in Effective Java. A fourth style, double-checked locking, also works if the field is declared volatile, but it is easy to get wrong, so prefer the three above.

C++11 and later make lazy singletons easy. The language guarantees that a function-local static variable is initialized exactly once, even when several threads call at the same time:

C++
class Logger {
public:
    static Logger& instance() {
        static Logger theOnly;       // thread-safe lazy initialization
        return theOnly;
    }
    Logger(const Logger&) = delete;
    Logger& operator=(const Logger&) = delete;

    void log(const std::string& message);

private:
    Logger() = default;
};

This is often called the Meyers singleton. It still leaves the question of destruction order at program exit if one singleton uses another, so keep singletons independent. All these Java and C++ snippets are read-only here, because the examples are about compiler and memory-model guarantees rather than printed output.

Modules are singletons already

In Python, a module is executed once on the first import, and every later import gets the same module object from sys.modules. A module-level variable is therefore a natural singleton:

Python
# settings.py
config = {"theme": "light", "language": "en"}

# anywhere else
from settings import config   # always the same dict

ES modules in JavaScript behave the same way: the module body runs once, and every importer shares its exports. Often the best "singleton" is simply an exported object with no class machinery at all.

JS A module-style singleton with a testing problem

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Why Singleton is often an anti-pattern

Critics point to several problems, and they are worth taking seriously.

  • Hidden dependencies. A class that calls Config.getInstance() internally does not show, in its constructor or signature, that it depends on configuration. Readers must scan the body to find out.
  • Global mutable state. Anyone can change the instance, so bugs appear far from their cause. The example above showed how one test pollutes the next.
  • Hard to test and substitute. You cannot easily replace the instance with a fake, and tests that run in parallel can interfere.
  • It enforces two rules at once. "Only one instance" and "global access" are separate decisions, and the pattern fuses them. You may want one instance without letting everyone reach it.
  • Rigid under change. The day you need two (per tenant, per test, per thread), the whole codebase calls getInstance().

The better alternative is usually: create one object at startup (in the composition root) and pass it to whoever needs it. You still have one instance, but nothing enforces it, nothing is global, and tests can pass a fake. Use a true Singleton only for things that are inherently unique and stateless or read-only, such as a logger front-end or a hardware handle, and even then consider injecting it.

If you find yourself writing getInstance() calls scattered across many classes, stop and ask whether those classes should receive the object as a parameter instead. Introducing a singleton is quick; removing one from a mature codebase is slow.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What are the two guarantees of the Singleton pattern?

    Singleton restricts a class to one instance and provides global access to it.
  2. 2. What is the difference between eager and lazy initialization?

    Eager initialization builds the instance up front, while lazy initialization waits until getInstance() is first called.
  3. 3. Why is the naive Java lazy singleton unsafe?

    Without synchronization the null check and the assignment are not atomic, so a race can create two instances.
  4. 4. Why is a module in Python or JavaScript often a good singleton?

    Both module systems cache the loaded module, so module-level state is shared without any extra class machinery.
  5. 5. What is the usual recommended alternative to a global Singleton?

    Passing the single object to its users keeps one instance but removes global access and makes testing with fakes easy.

Summary

  • Singleton restricts a class to one instance and offers global access to it.
  • Eager creation is simple and thread safe; lazy creation saves work but needs care with threads.
  • Java: prefer an enum, the holder idiom or eager init. C++11: a function-local static is thread safe.
  • Python and JavaScript modules are already singletons.
  • Drawbacks: hidden dependencies, global mutable state, painful tests, rigidity.
  • Prefer creating one object at startup and injecting it.

Next lesson: Factory Method.