The Singleton Pattern
You'll learn how to ensure a class has only one instance throughout your application and provide a single, global access point to it.
What Is the Singleton Pattern?
The Singleton pattern guarantees that a class creates exactly one instance and provides a consistent way to access it. Think of it like a government's presidential office—there's only ever one president at a time, and everyone knows how to reach that office.
This is useful for managing shared resources like configuration objects, database connections, or logging services where multiple instances would cause conflicts or waste resources.
Implementation with Classes
JavaScript doesn't enforce singletons natively, but you can implement them using encapsulation techniques you've already learned:
class DatabaseConnection {
static #instance = null;
constructor() {
if (DatabaseConnection.#instance) {
return DatabaseConnection.#instance;
}
this.connected = false;
DatabaseConnection.#instance = this;
}
connect() {
this.connected = true;
console.log('Connected to database');
}
}
const db1 = new DatabaseConnection();
const db2 = new DatabaseConnection();
console.log(db1 === db2); // true — same instance!
Module-Based Singleton
A simpler approach uses module scope:
// config.js
let instance = null;
export function getConfig() {
if (!instance) {
instance = {
apiUrl: 'https://api.example.com',
timeout: 5000
};
}
return instance;
}
Every import gets the same configuration object.
When to Use Singletons
Use singletons sparingly—they're essentially global state, which can make testing harder. They're best for truly shared resources like app configuration or connection pools.
Key Takeaway: The Singleton pattern uses constructor logic or module scope to ensure only one instance exists, providing controlled global access—but use it judiciously to avoid hidden dependencies.