Sobes.tech
Junior — Middle

Can you explain the working principle of the Singleton pattern and its main features?

sobes.tech AI

Answer from AI

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

Main features:

  • Control over object creation — the instance is created only once.
  • Global accessibility — the object is accessible from any part of the program.
  • Used for managing shared resources, such as database connections or configuration.

Example of Singleton implementation in JavaScript (Node.js):

class Singleton {
  constructor() {
    if (Singleton.instance) {
      return Singleton.instance;
    }
    this.value = Math.random();
    Singleton.instance = this;
  }
}

const a = new Singleton();
const b = new Singleton();
console.log(a === b); // true

Here, creating a second object returns the already existing instance.