Singleton Design Pattern JavaScript
JavaScript: Singleton Design Pattern with Real Time Example
Singleton Design Pattern:
It is Creational Patterns which focus on how to instantiate an object.
Singleton Design Pattern ensure that a class has only one instance, and provides a way to access it globally.
In other words, Singletons are used to create an instance of a class if it does not exist or else return the reference of the existing one.
You may also like Node.js Interview Questions
Singleton Design Pattern - JavaScript
- Singleton Design Pattern using IIFE
- Singleton Design Pattern using ES6 Class
Singleton Design Pattern using IIFE
var Singleton = (function () {
var instance;
function createInstance() {
var object = new Object();
return object;
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
},
};
})();
var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();
console.log(instance1 === instance2); //true
You may also like React.js Interview Questions
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
Singleton Design Pattern - 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);