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