Quiz

Explain the concept of the Singleton pattern

Topics
JavaScript
在GitHub上编辑

TL;DR

The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. This is useful when exactly one object is needed to coordinate actions across the system. In JavaScript, this can be implemented using closures or ES6 classes.

class Singleton {
constructor() {
if (!Singleton.instance) {
Singleton.instance = this;
}
return Singleton.instance;
}
}
const instance1 = new Singleton();
const instance2 = new Singleton();
console.log(instance1 === instance2); // true

Singleton pattern

The Singleton pattern is a design pattern that restricts the instantiation of a class to one single instance. This is particularly useful when exactly one object is needed to coordinate actions across the system.

Key characteristics

  • Single instance: Ensures that a class has only one instance.
  • Global access: Provides a global point of access to the instance.
  • Lazy initialization: The instance is created only when it is needed.

Implementation in JavaScript

There are several ways to implement the Singleton pattern in JavaScript. Here are two common methods:

Using closures

const Singleton = (function () {
let instance;
function createInstance() {
const object = new Object('I am the instance');
return object;
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
},
};
})();
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // true

Using ES6 classes

class Singleton {
constructor() {
if (!Singleton.instance) {
Singleton.instance = this;
}
return Singleton.instance;
}
}
const instance1 = new Singleton();
const instance2 = new Singleton();
console.log(instance1 === instance2); // true

Use cases

  • Configuration objects: When you need a single configuration object shared across the application.
  • Logging: A single logging instance to manage log entries.
  • Database connections: Ensuring only one connection is made to the database.

Further reading

在GitHub上编辑