Singleton Design Pattern JavaScript

Home >> Blog >> Singleton Design Pattern JavaScript

What is the Singleton Design Pattern in JavaScript?

Singleton Design Pattern ensure that a class has only one instance, and provides a way to access it globally.

In other words, Singleton Design Pattern are used to create and ensure only single instance of a class.

It is a type of Creational Patterns which focus on how to instantiate an object.

Implementation of Singleton Design Pattern - JavaScript
  1. Singleton Design Pattern using IIFE (Immediately Invoked Function Expression)
  2. Singleton Design Pattern using ES6 Class
You may also like - Architectural Patterns vs Design Patterns (In Details)
1. Implementation of Singleton Design Pattern - using IIFE
const Singleton = (function () { let instance; function createInstance() { let object = new Object(); return object; } return { getInstance: function () { if (!instance) { instance = createInstance(); } return instance; }, }; })(); const instance1 = Singleton.getInstance(); const instance2 = Singleton.getInstance(); console.log(instance1 === instance2); //true
You may also like JavaScript Interview Questions [Advanced]
2. Implementation of Singleton Design Pattern - using ES6 Class
//First Approach class Singleton { static instance; constructor () { if (!Singleton.instance) { Singleton.instance = this; Object.freeze(Singleton.instance); } return Singleton.instance } } const instance1 = new Singleton(); const instance2 = new Singleton(); console.log(instance1 === instance2);//true //Second Approach: class Singleton { static instance; constructor(server = null) { this.server = server; } static dbConnection() { if (!Singleton.instance) { Singleton.instance = new Singleton(); Object.freeze(Singleton.instance); } return Singleton.instance; } } const instance1 = Singleton.dbConnection(); const instance2 = Singleton.dbConnection(); console.log(instance1 === instance2); //true

Additionally, Learn how to implement singleton design pattern in PHP

Implementation of Singleton Design Pattern - In PHP
class SingletonDB { private static $obj; private final function __construct() { echo __CLASS__ . " initialize only once "; } public static function getInstance() { if (!isset(self::$obj)) { self::$obj = new SingletonDB(); } return self::$obj; } } $obj1 = SingletonDB::getInstance(); $obj2 = SingletonDB::getInstance(); var_dump($obj1 == $obj2);
You may also like Node.js Interview Questions