Skip to main content
Design Patterns 70 XP · 6 min

Singleton: The Single Instance

Ensure a class has only one instance and provide a global access point — but overuse creates hidden global state and makes testing painful.

Showing
Ad (728×90)

Why this matters

Singleton is one of the most misused patterns. When it works: a config manager, logger, or connection pool — one shared instance is genuinely needed. The trap is using Singleton as a shortcut for global state. The instance becomes invisible coupling: every class that calls getInstance() is secretly coupled to the concrete class, and tests cannot substitute a fake without monkey-patching.

The problem

Bad

The solution

Good

Thread safety and Python modules

In Python, modules are singletons by default — importing the same module twice returns the same object. A module-level instance is the idiomatic approach. In TypeScript, ES modules behave the same way. Before reaching for a Singleton class, ask whether a module-level constant already solves the problem.

Key takeaway

If your Singleton makes unit tests require real infrastructure, it has become an anti-pattern — inject the dependency instead so callers and tests can both supply what they need.

Done with this lesson?

Mark it complete to earn XP and track your progress.