Singleton Design Pattern Explained
The Singleton pattern ensures a class has only one instance throughout an application's lifetime, and provides a single global point of access to it.
Published October 6, 2026
The Singleton pattern ensures a class has only one instance and provides a global access point to it. It is used for shared resources such as configuration or a connection pool, but overuse makes code hard to test.
The concept
The constructor is made private (or hidden) and the class holds the single instance, creating it on first use.
Singletons behave like global state: hidden dependencies, hard to mock and tricky with threads. Dependency injection is often a better way to share one object.
Same object every time
Practical examples
JavaScript module (idiomatic)
// config.js
export default Object.freeze({ apiUrl: process.env.API_URL })Classic class
class DB {
static #inst
static get() { return DB.#inst ??= new DB() }
#constructor() {}
}PHP
final class Config {
private static ?Config $i = null;
private function __construct() {}
public static function get(): self { return self::$i ??= new self(); }
}Common mistakes
- Using Singletons as a global dumping ground.
- Not considering thread safety.
- Making unit tests depend on shared state.
Key takeaways
- One instance, global access.
- Modules already act as singletons in JS.
- Prefer dependency injection.
FAQ
Is Singleton an anti-pattern?
Often criticised for global state, but valid for truly single resources.
How do I test it?
Provide a reset method or inject the dependency instead.