| name | apply-singleton-pattern |
| description | Use when exactly one instance of a class must exist across the entire application — such as a configuration store, connection pool, or logger — and global access to that instance is required. |
Apply Singleton Pattern
Ensure a class has exactly one instance and provide a global access point to it.
Why This Is Best Practice
Adopted by: Spring Framework (default bean scope is singleton — the most-used Java
framework, 65%+ of Java enterprise apps per JetBrains 2023 survey), Python's logging
module (each getLogger(name) returns the same Logger instance for that name), Go's
sync.Once (idiomatic Go singleton construction), and Java Runtime.getRuntime()
(JVM runtime singleton, in every JVM since Java 1.0).
Impact: GoF documents that uncontrolled global state causes initialization ordering
bugs and duplicate resource allocation. Connection pools (HikariCP, the most-used Java
connection pool) are singletons by necessity — two pools to the same DB double
connections and break max-connection limits.
Why best: The alternative — passing the shared instance everywhere via constructor
(dependency injection) — is architecturally cleaner and preferred when testability
matters. Singleton is correct when the instance is a true system-level resource (one
config, one log system, one thread pool) and DI wiring overhead is unjustified.
Sources: Gamma et al. (1994) pp. 127–136; Spring Framework documentation (Bean scopes);
Go sync.Once documentation; HikariCP design rationale
Steps
Step 1: Make the constructor private (or restrict it)
class Configuration:
_instance: "Configuration | None" = None
def () -> :
cls._instance :
cls._instance = ().__new__(cls)
cls._instance._initialized =
cls._instance
():
._initialized:
._data: = {}
._initialized =