Dhananjay Patel Logo
  1. Home
  2. / Blog
  3. / Design Pattern
  4. / Lessons
  5. / 4

Singleton Pattern

The Singleton pattern ensures that a class has only one instance and provides a global point of access to it.

When to Use:

Use the Singleton pattern when you need exactly one instance of a class to control the actions, such as in logging, managing a connection pool, or in cases where a single instance should coordinate actions across the system.

Example

class Singleton {
private static instance: Singleton;
private constructor() {}
public static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
public someBusinessLogic() {
console.log('Executing some business logic.');
}
}
// Usage
const singleton1 = Singleton.getInstance();
const singleton2 = Singleton.getInstance();
console.log(singleton1 === singleton2); // Output: true

Pros:

  • Controlled access to the sole instance.
  • Reduced memory footprint as the instance is created only once.

Cons:

  • Can introduce global state into an application, which can lead to hard-to-debug issues.
  • Makes unit testing difficult due to the tight coupling of code to the Singleton instance.