Learn

Architecture & pattern guides

Read the idea, build it on a Grid, prove it in a challenge. Short, practical guides — illustrated with RodGrid's own nodes — on system design, design patterns, flow modeling, and how to get the most out of the app.

All articles

Singleton

Keep exactly one instance of a class with one global point of access to it, and know the price: a dependency no signature shows, state every caller shares, tests that leak into each other, and a first call that needs care when threads race.

One registry per process

A web service publishes its metrics at /metrics: request counts, latencies, cache hit rates. Every handler that counts something registers its counters in a metrics registry, and the /metrics endpoint reads that registry and prints everything in it. All of them have to use the same one. If the checkout handler registers its counter in one registry while the endpoint reads another, the counter goes on counting and never reaches a dashboard, and nothing reports an error.

Singleton is one answer: a class that has exactly one instance and gives the rest of the program one global point of access to it. MetricsRegistry makes its constructor private, so no other code can call new MetricsRegistry(), and keeps its one instance in a static field. A static method, MetricsRegistry.getInstance(), returns that instance, creating it on the first call. Any code anywhere in the process can call it, and every caller gets the same object.

One instance, shared by every caller.

Every caller, one registry

Nobody passes the registry around. Each caller asks the class for it and gets the same object.

What the global access costs

The convenience is that any function can reach the registry without anyone handing it over. Each cost of the pattern comes from that same convenience.

  • The dependency is hidden. chargeCard(order) increments a counter on MetricsRegistry.getInstance() somewhere in its body. Its signature says it needs an order and says nothing about the registry, so the only way to learn what the function touches is to read it, and every function it calls.
  • The state is shared by every caller. The registry is mutable, and every thread in the process writes to it, so its counters must be safe to update concurrently. A setting one caller changes, such as a label added to every metric, changes for all of them.
  • Tests leak into each other. The instance lives as long as the process, and a test runner usually runs many tests in one process. A test that registers a payments_total counter leaves it behind, and the next test that registers the same name fails with a duplicate-metric error. Each test passes on its own; the failure depends on which ran first.

The usual patch is a reset() method that tests call between runs. It works, and it is also a method any production code can call. It does not help tests that run in parallel threads of one process either, because they use the one instance at the same moment.

Watch outSingletons are global state, which makes testing and concurrency harder. The common mistake is reaching for one because global access is convenient, not because a single instance is a genuine invariant. A CurrentUser singleton in a web server holds one user for every request it is serving at once, and a request can read the wrong person's data. Use Singleton only when a second instance would itself be a bug, not merely because callers must share one: here every caller needs the same registry, and passing one instance in, shown below, gives that too.

The first call, from two threads

Creating the instance on first use is called lazy initialisation, and the check inside getInstance() takes two steps: look at the field, create the instance if it is empty. If two threads make the first call at the same moment, both can find the field empty and each build a registry; one of them ends up in the field, and the counters registered through the other never reach /metrics.

Creating the instance eagerly when the class loads closes that gap by giving up laziness. Thread-safe lazy initialisation closes it and keeps creation on first use, by guarding the check with a lock or by leaning on the language: Java runs a class's static initialisation once even when threads race to trigger it (the usual idiom keeps the instance in a small holder class that only getInstance() touches), and C++ since C++11 does the same for a static local variable. A hand-written double-checked lock is easy to get wrong (in Java the field must be volatile); locks themselves are taught in Mutex and semaphore.

One instance, passed in

Most of what Singleton gives can be had without the global access point. Create one MetricsRegistry at startup, in the code that wires the application together, and hand it to each handler through its constructor. There is still exactly one, because only one place creates it. The checkout handler's constructor now lists the registry, so the dependency is visible, and each test builds a fresh registry of its own, so nothing leaks from one test into the next. That is Dependency Injection, and it removes most of the costs above. DI containers even call this lifetime "singleton", meaning one instance per container, not a class that enforces it.

What the injected version gives up is enforcement: nothing stops someone from writing a second new MetricsRegistry(). When the single instance matters that much, some teams keep the Singleton and call getInstance() only in the startup code, passing the instance inward from there as an interface the registry implements, so tests can give the rest of the code a fake registry of their own. A related idea, sharing one object per distinct value rather than one per class, is Flyweight.

Three callers, one box

The Singleton Pattern Challenge allows six nodes and asks for a Singleton participant with one shared instance, several clients or actors reaching that same instance, the single global access point made clear, and controlled instantiation instead of direct construction. Draw the registry as the Singleton node and two or three callers as Component or Actor nodes, each with an edge labelled getInstance() to that one node. Controlled instantiation needs a visible sign, not only a missing edge: every caller's edge says getInstance(), none creates the registry, and the Singleton node's title can name the private constructor.

Practice this