Singleton Design Pattern in JavaScript

1. Definition

The Singleton Design Pattern ensures that a class has only one instance and provides a global point of access to that instance. It involves a single class responsible for creating an instance of itself while ensuring no other instance can be created.

2. Problem Statement

Imagine you want to have a single configuration object in your application. If multiple instances of this configuration object were mistakenly created, it could result in inconsistencies in the system's behavior and values.

3. Solution

To ensure only one instance of a class is ever created, the Singleton pattern restricts the instantiation of a class to a single object and provides a method to retrieve its sole instance.

4. Real-World Use Cases

1. Database Connections: Ensuring an application uses a shared database connection instead of opening multiple connections.

2. Logger: Ensuring that logging to a file or console uses a single logger instance.

3. Configuration Manager: Managing settings and configurations used throughout an application.

5. Implementation Steps

1. Create the Singleton class with a private static variable to hold the single instance of the class.

2. Make the constructor private to prevent direct instantiation.

3. Provide a static method to get the single instance of the class.

6. Implementation in JavaScript

// Singleton class
class Singleton {
  // Private static variable to hold the single instance
  static instance;
  // Private constructor
  constructor(data) {
    if (Singleton.instance) {
      return Singleton.instance;
    }
    Singleton.instance = this;
    this.data = data;
  }
  // Static method to get instance
  static getInstance(data) {
    if (!Singleton.instance) {
      Singleton.instance = new Singleton(data);
    }
    return Singleton.instance;
  }
}
// Client code
const instance1 = new Singleton('Data for instance 1');
const instance2 = new Singleton('Data for instance 2');
console.log(instance1 === instance2); // true
console.log(instance1.data); // Data for instance 1

Output:

true
Data for instance 1

Explanation:

1. The Singleton class has a private static variable called instance to hold its sole instance.

2. The constructor checks if an instance already exists. If it does, it returns the existing instance; otherwise, it assigns the current object to the instance.

3. The static getInstance method ensures that there's only one instance of Singleton and returns it. If there's no existing instance, it creates one.

4. In the client code, even though we attempt to create two instances of the Singleton class, we only get one instance.

7. When to use?

Use the Singleton pattern when:

1. There must be exactly one instance of a class, and it must be easily accessible to clients.

2. The single instance should be extendable by subclassing, and clients should be able to use an extended instance without modifying their code.


Comments