Singleton Pattern
In one line
The Singleton pattern restricts a class to a single instance and provides a global access point to it.
In simple words
The Singleton pattern guarantees that a class has exactly one instance and provides a global way to access it. This is useful when exactly one object is needed to coordinate actions across the system — a database connection, a logger, a configuration manager, or a hardware driver.
The pattern works by making the constructor private (or guarded) so external code cannot call new directly, and exposing a static method (often called getInstance()) that returns the existing instance or creates it on the first call. All subsequent calls return the same object.
Singletons are controversial because they introduce global state, which makes testing harder and can hide dependencies. Use it sparingly — only when you genuinely need a single shared instance, not as a default way to access things.
Example
class Logger {
static #instance = null;
static getInstance() {
if (!Logger.#instance) Logger.#instance = new Logger();
return Logger.#instance;
}
log(msg) { console.log(`[LOG] ${msg}`); }
}
Logger.getInstance().log("hello"); // [LOG] hello
Logger.getInstance().log("world"); // [LOG] worldLogger.getInstance() always returns the same Logger instance. The private static field #instance caches it.
Related terms
Related Resources
Related Lessons
- Design Patterns
Singleton is a creational pattern.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.