Singleton
Ensure a class has exactly one instance and provide a global access point to it — useful for shared resources like config, logging, or DB connections.
Intent & Description
🎯 Intent
Guarantee that only one instance of a class ever exists and provide a single, well-known access point to it.
📋 Context
You have a database connection pool, configuration manager, or logger that should be initialized once and reused everywhere. Multiple instantiations would cause connection leaks, config conflicts, or duplicate log entries.
💡 Solution
The class checks at construction time whether an instance already exists. If it does, return it; if not, create and store it. The constructor is effectively bypassed after the first call. The single instance is accessible globally through the class itself.
Real-world Use Case
Source
📌 TL;DR
One instance, globally accessible. Practical for loggers and DB pools. A global variable with extra steps — test isolation becomes a headache. Use with intention, not habit.
Advantages
- Controlled access — one instance, one place to manage it.
- Lazy initialization — created only on first use, not at startup.
Disadvantages
- Global state in disguise — makes unit testing hard because state bleeds between tests.
- Violates Single Responsibility Principle — the class manages its own instantiation on top of its actual job.
- Can mask bad design — classes that ’need’ a singleton often just have too many responsibilities.
class DatabaseConnection {
constructor() {
if (DatabaseConnection.instance) {
return DatabaseConnection.instance;
}
this.connectionString = "mongodb://localhost:27017/db";
DatabaseConnection.instance = this;
}
query(sql) {
console.log(`Executing: ${sql}`);
}
}
const instance1 = new DatabaseConnection();
const instance2 = new DatabaseConnection();
console.log(instance1 === instance2); // true