Singleton makes a class responsible for having exactly one instance, and gives everyone a global way to reach it: a private constructor plus a static getInstance() that creates the object on first use and returns the same one every time after. It solves a real problem (two parts of a program each building their own copy of something that must be shared), but it does so with global state, which makes dependencies invisible and tests harder. That is why it is both one of the best-known patterns and the one most often listed as an anti-pattern. Learn it, learn its costs, and usually reach for Dependency Injection instead.
Think of it like
The office's one shared calendar
A team keeps its meetings in one shared calendar. If each person kept a private paper copy, someone would book a room on their copy and nobody else would see it. The shared calendar fixes that, but notice what it costs: anyone can change it from anywhere, you cannot tell who depends on it by looking at their desk, and if you want to rehearse a planning session you cannot get a blank calendar without wiping everyone's meetings.
The problem
A small app has a theme setting. A ThemePicker lets the user switch to dark mode, and a Header draws itself in the current theme. Both need the app's configuration, and the obvious code lets each one create its own. This is the Before version in the visualizer above.
class AppConfig {
private theme = "light";
setTheme(t: string) {
this.theme = t;
}
getTheme() {
return this.theme;
}
}
class ThemePicker {
private config = new AppConfig();
pick(t: string) {
this.config.setTheme(t);
}
}
class Header {
private config = new AppConfig();
render() {
return "header: " + this.config.getTheme();
}
}
const picker = new ThemePicker();
const header = new Header();
picker.pick("dark");
header.render(); // "header: light", not dark!Run it in the visualizer and look at the objects view: two AppConfig objects appear, config (owned by picker) and config2 (owned by header). The picker sets theme = "dark" on its own copy, and the header keeps reading "light" from the other one. Nothing crashed; the program is simply wrong, which is the worst kind of bug.
- Two sources of truth. Settings, caches, connection pools, counters or an in-memory registry only work if everyone sees the same object.
- Wasted resources. Some objects are expensive or exclusive: a pool of database connections, a handle to a hardware device, a file that only one writer may hold open. Creating one per caller is slow or outright broken.
- Nobody is in charge of creation. Any class can call
new, so "there is one" is only a hope, enforced by nothing.
The pattern
Intent (after the Gang of Four book): ensure a class has only one instance, and provide a global point of access to it.
- Singleton (
AppConfig) - The class that must have one instance. Its constructor is private, so no other code can call
new AppConfig(). - Static instance field (
instance) - A class-level field that holds the one object. It starts empty (
null) in the lazy form. - Static accessor (
getInstance()) - The only way to get the object. The first call creates it and stores it in
instance; every later call returns that same object. - Clients (
ThemePicker,Header) - Code that calls
AppConfig.getInstance()wherever it needs the config, instead of receiving it as a parameter.
In UML, static (class-level) members are underlined, like instance and getInstance() in the class diagram above. They belong to the class, not to any object, which is exactly why every caller reaches the same instance.
What the visualizer shows
- Class diagram:
AppConfigwith its private constructor- AppConfig()and its underlined static members. WhengetInstance()runs, that line lights up. - Objects at runtime: besides ordinary objects such as
picker : ThemePicker, there is a box labelledAppConfig «class». It is the class itself, holding its static field. Before anything runs it showsinstance = null; after the first call it showsinstance = config, with an arrow to the oneconfigobject. By the end, three arrows (picker.config,header.configandAppConfig.instance) all point to the same box. - Sequence of calls: the
AppConfig «class»lane is there from the start, because a class exists before any of its objects. The firstgetInstance()call sends a «create» toconfig; the second one comes straight back with the same object.
The Before / With Singleton toggle compares the two programs, and Fresh config in tests applies a change request to whichever version is shown. The objects counter under the stage counts objects only, not the class box: 3 with Singleton (picker, header and one config) against 4 before (two configs).
Walkthrough
- 1
The class exists, the instance does not
With With Singleton selected, the first frame already shows
AppConfig «class»withinstance = null. Static fields are initialized when the class is defined, before any object exists. - 2
A client asks the class
new ThemePicker()runs its field initializer, which callsAppConfig.getInstance(). The message goes to the class itself, not to an object. - 3
First call: create and remember
instanceis empty, sogetInstance()runsnew AppConfig()(allowed: the private constructor is called from inside the class).configappears withtheme = "light", andAppConfig.instancenow points to it. - 4
Hand it out
getInstance()returnsconfigandpicker.configpoints to it. - 5
Second call: no new object
new Header()callsgetInstance()again. This timeinstanceis already set, so no object is created and the sameconfigcomes back.header.configpoints to it too. - 6
One change, seen by everyone
picker.pick("dark")setsconfig.themeto"dark". Thenheader.render()asksconfig.getTheme()and gets"dark", so it returns"header: dark". Compare Before, where the same calls return"header: light". - 7
Change request: a fresh config for test 2
Apply Fresh config in tests. A second test needs the default theme, but the one instance still says
"dark".AppConfig.resetForTests()setsinstanceback tonull, and the nextgetInstance()createsconfig2with"light". Look at the objects view:pickerandheaderstill point to the oldconfig. A reset only helps code that has not already cached the instance.
Before and after
Each part makes its own
ThemePickerandHeadereach hold a differentAppConfig- The header never sees the theme the picker set
- Nothing stops more copies from being created
- Each test gets fresh state for free
- Dependencies are created inside the class, so they are still hidden
With Singleton
- Exactly one
AppConfig; the private constructor enforces it - Every caller sees the same state
- The instance is created lazily, on first use
- State outlives each test: tests need a reset hook and run in a fixed order
- Callers reach a global, so dependencies are invisible in their signatures
| Change request: fresh config in tests | Before | With Singleton |
|---|---|---|
| Existing classes edited | 0 | 1 (AppConfig) |
| New classes | 0 | 0 |
| Lines changed in existing classes | 0 | 3 (+3 −0) |
This is one of the rare change requests where the code without the pattern wins. Plain objects start from their defaults, so the Before test just creates a new AppConfig. The Singleton version has to add a test-only resetForTests() method to production code (three lines), every test must remember to call it, and as the visualizer shows, objects that cached the old instance keep using it. Singleton fixed the shared-state bug and paid for it in testability.
Variations
Eager or lazy
Eager creates the instance when the class or module loads (static final AppConfig INSTANCE = new AppConfig();). It is simple and thread-safe because the language runtime initializes it once, but it pays the creation cost even if nobody uses it. Lazy creates it on the first getInstance() call, as in the visualizer. Lazy is only worth it when creation is expensive and might not be needed; and in languages with shared-memory threads it needs care, because two threads can both see instance == null and both create one.
Thread-safe lazy initialization
| Technique | Language | How it stays safe |
|---|---|---|
synchronized getInstance() | Java | Every call takes a lock. Correct and simple; the lock is cheap when uncontended, so this is fine unless getInstance() is truly hot. |
| Initialization-on-demand holder | Java | getInstance() returns Holder.INSTANCE, a static field of a nested class. The JVM initializes Holder on first use, once, with its own locking (class initialization in the Java Language Specification), so no explicit lock is needed. |
| Enum singleton | Java | enum AppConfig { INSTANCE; ... }. The JVM guarantees one instance per enum constant, Java serialization keeps it unique, and reflection cannot create enum instances. Joshua Bloch's Effective Java recommends it. It is eager and cannot extend another class. |
| Double-checked locking | Java, C++, others | Check without the lock, lock, check again, create. In Java the field must be volatile (correct since Java 5), or another thread can see a reference to a half-built object. Details in Double-Checked Locking. |
| Function-local static (Meyers singleton) | C++ | static AppConfig instance; inside getInstance(). Since C++11 the language guarantees it is initialized exactly once, and other threads wait until it is ready. |
| Module-level instance | Python | config = AppConfig() at the top of config.py. A module runs once and is cached in sys.modules, and the import system locks a module while it initializes, so every importer gets the same object. |
| Module singleton | JavaScript / TypeScript | export const config = new AppConfig();. A module is evaluated once per module specifier (resolved path), and JavaScript runs your code on one thread, so there is no race. Watch out: two different resolved paths (or two copies of a package in node_modules) give two instances. |
sync.Once, object, Lazy<T> | Go, Kotlin, C# | Go's sync.Once runs an initializer exactly once; a Kotlin object declaration is a language-level singleton; C#'s Lazy<T> is thread-safe by default. |
// 1. Holder idiom: lazy, no explicit locks.
final class Registry {
private Registry() {}
private static final class Holder {
static final Registry INSTANCE = new Registry();
}
static Registry getInstance() { return Holder.INSTANCE; }
}
// 2. Enum: eager, safe against serialization and reflection.
enum Settings {
INSTANCE;
private volatile String theme = "light";
String theme() { return theme; }
void setTheme(String t) { theme = t; }
}
// 3. Double-checked locking: needs volatile.
final class Pool {
private static volatile Pool instance;
private Pool() {}
static Pool getInstance() {
Pool p = instance; // one volatile read
if (p == null) {
synchronized (Pool.class) {
p = instance;
if (p == null) {
p = new Pool();
instance = p;
}
}
}
return p;
}
}In real code
| Where | What is single | Notes |
|---|---|---|
| Java | Runtime.getRuntime() | Its documentation says every Java application has a single instance of Runtime; the constructor is private. |
| Java | java.awt.Desktop.getDesktop() | Returns the one Desktop instance for the current desktop context. |
| Python | None, True, False, NotImplemented, Ellipsis | Single objects of their types, which is why x is None works. |
| Python logging | logging.getLogger() | With no name it returns the root logger; calls with the same name always return the same Logger object. Strictly a multiton: one instance per name. |
| Spring | Beans in the default singleton scope | One instance per container, created and injected by the container. Classes receive it through constructors, so it is a container-managed singleton, not the GoF pattern. |
| Node.js | Any module's exports | Modules are cached after the first require or import, so export const db = new Pool() is shared by every importer of that resolved file. |
In application code the usual candidates are configuration, a logger (see Design a Logging Framework), a connection pool, a cache, a metrics registry, a feature-flag client and a hardware or OS handle. Most mature codebases still create these once, but at startup, and pass them in instead of calling getInstance() from everywhere.
When to use it, and when not to
A Singleton can be reasonable when
- There must be exactly one, for a real reason: one OS resource, one hardware device, one process-wide registry
- The object is stateless or effectively immutable after startup (a logger facade, read-only config)
- You have no DI container and the codebase is small, and you keep
getInstance()calls at the edges - A library has to offer a default instance that works without setup (and still lets callers pass their own)
Avoid it when
- You only want one instance in production: create it once and inject it instead
- The state is mutable and shared: every caller is now coupled through a global
- Code must be unit-tested in isolation or in parallel
- "One" might become "one per tenant, per request or per test" later
- It is a shortcut to avoid passing a parameter
- Hidden dependencies.
Header's constructor takes no parameters, yet it depends onAppConfig. You only find out by reading its body. With injection the dependency is in the signature. - Global mutable state. Any code can change the theme from anywhere, and the change is visible everywhere. Bugs become "who changed this, and when?"
- Testing. You cannot substitute a fake without a reset or setter hook, tests leak state into each other, the order of tests starts to matter, and tests cannot run in parallel in one process.
- Concurrency. A naive lazy
getInstance()can create two instances under a race, and the shared instance's own fields need synchronization too: making creation thread-safe does not make the object thread-safe. - Lifecycle and SRP. The class now does its real job and also controls how many of it exist and when they are created (SOLID Principles). It is hard to subclass, configure differently, or shut down and recreate.
Singleton vs similar patterns
| Approach | How many instances | How callers get it | Main difference from Singleton |
|---|---|---|---|
| Singleton (GoF) | Exactly one, enforced by the class | Class.getInstance(), from anywhere | The reference point for this table |
| Static class (all static members) | None: there is no object | Class.method() | Cannot implement an interface, be passed as a value, be replaced in tests or be created lazily with state |
| Monostate (Python's Borg) | Many objects | new Config() | All instances share static state, so uniqueness is in the data, not the object; looks like a normal class to callers, which hides the sharing even more |
| DI container singleton scope | One per container | Injected through constructors | Same "one instance", but no global access and no private constructor; tests build their own |
| Multiton / registry | One per key | getInstance(key) | Like logging.getLogger(name); a Singleton per key |
| Flyweight | One per distinct intrinsic value | Through a factory | Shares many small immutable objects to save memory; not about one global object |
| Object Pool | A fixed set, reused | Borrow and return | Manages several expensive objects; the pool itself is often a single injected instance |
Implementation
The scenario as a complete program: AppConfig with a private constructor and a lazy getInstance, ThemePicker and Header that both fetch it, and the test-only reset hook from the change request. Thread safety: JavaScript runs this code on one thread, so the lazy check cannot race. Java uses a synchronized getInstance (simple and correct) and a volatile theme field. Python uses a lock with a double check, because two threads can otherwise both see no instance. C++ uses a function-local static, which C++11 initializes exactly once, and a mutex for the theme; a Meyers singleton cannot be recreated, so its test hook resets the fields instead.
import threading
class AppConfig:
_instance = None
_lock = threading.Lock()
def __init__(self):
# Python has no private constructors; this guard stands in.
if AppConfig._instance is not None:
raise RuntimeError("use AppConfig.get_instance()")
self._theme = "light"
@classmethod
def get_instance(cls):
# Thread-safe lazy creation: a cheap check first, then a
# second check under the lock, so only one thread creates it.
if cls._instance is None:
with cls._lock:
if cls._instance is None:
cls._instance = cls()
return cls._instance
@classmethod
def reset_for_tests(cls):
# The change request: a test-only way back to a fresh instance.
with cls._lock:
cls._instance = None
def set_theme(self, theme):
self._theme = theme
def get_theme(self):
return self._theme
class ThemePicker:
def __init__(self):
self._config = AppConfig.get_instance()
def pick(self, theme):
self._config.set_theme(theme)
class Header:
def __init__(self):
self._config = AppConfig.get_instance()
def render(self):
return "header: " + self._config.get_theme()
if __name__ == "__main__":
picker = ThemePicker()
header = Header()
picker.pick("dark")
print(header.render()) # header: dark
print(AppConfig.get_instance() is AppConfig.get_instance()) # True
# Test 2 needs the default theme, so it resets the instance.
AppConfig.reset_for_tests()
print(AppConfig.get_instance().get_theme()) # light
print(header.render()) # header: dark (header kept the old one)Key takeaways
- Singleton = private constructor + static instance field + static
getInstance()that creates the object on first use and returns the same one afterwards. - It fixes "two copies of something that must be shared": in the visualizer, Before has two
AppConfigobjects and the header reads"light"; with Singleton there is one and it reads"dark". - It bundles two decisions: one instance (often right) and global access (usually the problem: hidden dependencies, shared mutable state, hard tests).
- The change request shows the cost: fresh state per test needs 0 class edits without the pattern and a 3-line test-only
resetForTests()with it, and cached references still point to the old instance. - Where threads share memory, make creation thread-safe (Java holder idiom or enum,
volatilewith double-checked locking, C++11 function-local static, a lock in Python); the instance's own fields still need synchronization. - Default to one instance created at startup and injected (a DI container's singleton scope); keep the GoF form for true process-wide resources.
Common pitfalls
- A lazy
getInstance()without synchronization in Java, C++ or Python: two threads both seenulland create two instances, or (with double-checked locking but novolatile) one thread sees a half-built object. - Mutable global state used as a convenient parameter: any code can change it, tests leak into each other and must run in a fixed order. If you need a reset hook, that is a sign it should be injected.
- Assuming "one" means one everywhere: it is one per process (per class loader in Java, per module instance in JavaScript), never one per cluster.
- Breaking uniqueness by accident: Java serialization creates a new object unless you add
readResolve(or use an enum), reflection can call a private constructor, and a cloneable singleton can be copied. - Calling
getInstance()deep inside business logic. Fetch it at the edge (or inject it) so the rest of the code receives it as a normal parameter.
Interview tips
- Write the thread-safe version unprompted, name it (holder idiom, enum, double-checked locking with
volatile, Meyers singleton) and say why it is safe. - Expect "what is wrong with Singleton?". Answer with hidden dependencies, global mutable state, testability and lifecycle, then propose one instance injected through constructors or a DI container's singleton scope.
- In LLD rounds (parking lot, logger, cache) do not make the main manager a Singleton by reflex. Say "one instance, created in main and passed in", and mention that a cluster needs leader election, not a Singleton.
Real-world applications
- Process-wide resources: the Java
Runtime, a handle to a device or the console, a process-wide registry. - Loggers and logging configuration (often a registry of named loggers, as in Python's
logging.getLogger(name)). - Application configuration, feature-flag clients, metrics registries and connection pools, ideally created once and injected.
- Language-level single values such as Python's
None,TrueandFalse. - Default instances offered by libraries, alongside constructors for callers who want their own.
Test yourself
In the visualizer's Before version, why does header.render() return "header: light" after picker.pick("dark")?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.