Singleton Pattern

What It Is
Why Use It?
- Only one instance should exist (e.g., a database connection).
- You want a global access point, but safer than using a global variable.
Real-World Analogy
Example (JavaScript-style pseudocode)
Javascript
class Database {
// Private static variable to hold the single instance
static #instance = null;
// Private constructor
constructor() {
if (Database.#instance) {
throw new Error("Use Database.getInstance() instead of new.");
}
console.log("Connecting to the database...");
// setup code here
}
// Static method to get the instance
static getInstance() {
if (!Database.#instance) {
Database.#instance = new Database();
}
return Database.#instance;
}
// Example method
query(sql) {
console.log(`Running query: ${sql}`);
}
}
// Usage
const db1 = Database.getInstance();
db1.query("SELECT * FROM users");
const db2 = Database.getInstance();
db2.query("SELECT * FROM orders");
console.log(db1 === db2); // true - same instance
What’s Happening:
- You can’t use new Database() because the constructor is private.
- You must use Database.getInstance() to get the object.
- Every time you call getInstance(), you get the same object.
When to Use
- You only want one object (e.g., logger, config, database).
- You want that object to be accessible globally.
- You want to control creation of the object.
Pros and Cons
- You get a single, consistent instance.
- Global access with controlled creation.
- Can delay creation until needed (lazy).
- Breaks Single Responsibility Principle (does two things).
- Can be hard to unit test or mock.
- In multithreading, extra care is needed to avoid multiple instances.