Design Patterns
Singleton Pattern
The Singleton Pattern is a creational design pattern.
On this page
Singleton Pattern in JavaScript
1. Definition
The Singleton Pattern is a creational design pattern.
It guarantees that only a single instance of a class or object exists for the entire lifetime of the application, and provides a global access point to that instance.
Example:
javascript
class Singleton {
static #instance: Singleton;
private constructor() { }
public static get instance(): Singleton {
if (!Singleton.#instance) {
Singleton.#instance = new Singleton();
}
return Singleton.#instance;
}
public someBusinessLogic() {
// ...
}
}
function clientCode() {
const s1 = Singleton.instance;
const s2 = Singleton.instance;
if (s1 === s2) {
console.log(
'Singleton works, both variables contain the same instance.'
);
} else {
console.log('Singleton failed, variables contain different instances.');
}
}
clientCode();
Sources:
2. Implementing the Singleton Pattern in JavaScript
a. Using an IIFE (Immediately Invoked Function Expression)
javascript
const Singleton = (function() {
let instance;
function createInstance() {
return { time: Date.now() }; // can be an object or a class
}
return {
getInstance: function() {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
// Usage
const obj1 = Singleton.getInstance();
const obj2 = Singleton.getInstance();
console.log(obj1 === obj2); // true
Explanation:
- When
Singleton.getInstance()is called, a new instance is created if none exists yet; otherwise the existing instance is returned. - There is only ever a single instance across the whole application.
b. Using an ES6 Class with a static member
javascript
class SingletonClass {
constructor() {
if (SingletonClass.instance) {
return SingletonClass.instance;
}
this.time = Date.now();
SingletonClass.instance = this;
}
}
// Usage
const a = new SingletonClass();
const b = new SingletonClass();
console.log(a === b); // true
Explanation:
- The first time
new SingletonClass()is called, the instance is created and stored inSingletonClass.instance. - Subsequent calls return the originally created instance.
3. Real-World Applications
- Keeping a single database connection in a backend application.
- Storing shared config, cache, or logger instances used across the whole app.
- Managing global application state.
4. Pros & Cons
Pros:
- Guarantees only one instance, avoiding wasted resources.
- Easy to access from anywhere in the code.
Cons:
- Violates the Single Responsibility Principle, since it takes on two responsibilities at once: the class's core business logic, and enforcing that only a single instance exists.
- Can make testing harder if the singleton holds state.
- Introduces a global dependency, which can make code harder to maintain if overused.
References:
