intermediate

Singleton

Restrict a service to one shared instance only when global lifecycle is intentional, testable, and safer than explicit injection.

Singleton restricts a class to one instance, often for process-wide registries, connection pools, or configuration readers. In modern applications it is frequently replaced by dependency injection containers that manage lifetime explicitly. Accept Singleton only when global uniqueness is a real invariant and tests can reset or substitute the instance.

On interviews: explain why Singleton complicates testing and parallel tests. Contrast with module-level constants and DI-scoped services.

Common pitfalls: hidden global mutable state; lazy initialization races; using Singleton to avoid designing boundaries.

The trade-off is flexibility versus complexity—know when the simpler path is enough.

Checklist:

  • Justify true need for one instance per process.
  • Make replacement possible in tests.
  • Avoid business logic inside Singleton holders.
  • Prefer framework-managed scopes when available.