Skip to main content

Sign in to CleanKata

Track your progress, earn XP, and unlock every lesson.

By signing in you agree to our Terms of Use and Privacy Policy.

Design Patterns70 XP6 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.

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.

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.

🔧 Some exercises may still have errors. If something seems wrong, use the Feedback button (bottom-right of the page) to report it — it helps us fix it fast.

Hint: If your Singleton makes unit tests require a real database, it has become an anti-pattern. Inject the dependency instead.

✗ Your version