What is singleton pattern?

JavaScript

Singleton Pattern

The singleton pattern ensures that a class can have only one instance and provides a single, global point of access to it. Think of it as a "one and only" object for a specific purpose in your application.

How It Works

The core idea is to control the class's instantiation process. The first time an object is requested from the class, it's created and saved. Every subsequent time, instead of creating a new object, the saved one is returned.

This is typically achieved by:

  • Making the constructor private (or controlling access to it).
  • Creating a static method (often called getInstance()) that handles the logic of creating and retrieving the instance.

JavaScript Example (ES6 Class) ⚙️

Here’s a common way to implement a singleton for managing an application's configuration.

In this example, no matter how many times you call new Configuration(), you always get back the very first instance that was created.


class Configuration {
constructor() {
// Check if an instance already exists
if (Configuration.instance) {
// If yes, return the existing instance
return Configuration.instance;
}

// If no, create a new one and store it
this.settings = { theme: 'dark', version: '1.0.0' };
Configuration.instance = this;
}

getSetting(key) {
return this.settings[key];
}
}

// --- Usage ---

// Both variables will point to the *exact same* object.
const config1 = new Configuration();
const config2 = new Configuration();

console.log(config1 === config2); // true

// You can access the settings from either variable
console.log(config1.getSetting('theme')); // 'dark'
console.log(config2.getSetting('version')); // '1.0.0'

// If you modify it through one variable, the change is reflected everywhere.
config1.settings.theme = 'light';
console.log(config2.getSetting('theme')); // 'light'

When to Use It

Singletons are useful for managing shared resources or global state, such as:

  • A database connection pool: You only want one pool manager for the entire application.
  • A logger: A single logging instance to handle all application logs.
  • Configuration/Settings Manager: A global object to hold and provide access to application settings.
  • An in-app service: Like a user authentication service that holds the current user's state.
00:00