Singletons is a pattern where only an instance of a class exist. Class is the key concept here, not object. A N-ton (multiton) is a pattern where there are only N instances of a class, type safe enumerations are an example.
“A Singleton is an object which can only be instantiated only once.”
Classes gets instantiated, not objects, and the singleton pattern is related to classes.
“A singleton pattern creates a new instance of a class if one doesn’t exist.”
This is the concept of lazy loading. Not every singleton is lazy loaded.
“JavaScript has always had singletons built-in to the language. We just don’t call them singletons, we call them object literal”.
While I agree that in JavaScript we can use Object literals to emulate a singleton, I don’t agree that Object literals are singletons. They are just instances of Object class. Singleton is a way to have one and only one instance of a class. In your definition every object is a singleton…
let instance = null;function User(name, age) {
if(instance) {
return instance;
}instance = this;
this.name = name;
this.age = age;
return instance;
}const user1 = new User('Peter', 25); // Oh my...
const user2 = new User('Mark', 24); // Oh my...
Singleton with parameters? Really? No way!
A very simple singleton JavaScript:
function MySingleton() {
return MySingleton;
}
or
class MySingleton {
constructor() {
return MySingleton;
}
}
The above MySingleton
is indeed a singleton, but it is not lazy loaded.