Below is an example of a very popular implementation of the JavaScript Singleton pattern:
var mySingleton = (function() {
var instance;
function init() {
function privateMethod() {
console.log("I am private");
}
var privateVariable = "Im also private";
var privateRandomNumber = Math.random();
return {
publicMethod: function() {
console.log("The public can see me!");
},
publicProperty: "I am also public",
getRandomNumber: function() {
return privateRandomNumber;
}
};
};
return {
getInstance: function() {
if (!instance) {
instance = init();
}
return instance;
}
};
})();
I have been thinking about it for a while and don't really understand the need of this complexity when we can achieve the same result with this simple code:
singleton = (function() {
var obj = {
someMethod: function() {}
}
return obj;
}());
Am I overlooking something here?
Singleton design pattern exposes a single instance that can be used by multiple components. Singleton is a design pattern that tells us that we can create only one instance of a class and that instance can be accessed globally. This is one of the basic types of design pattern.
Singletons reduce the need for global variables which is particularly important in JavaScript because it limits namespace pollution and associated risk of name collisions.
Use the Singleton pattern when a class in your program should have just a single instance available to all clients; for example, a single database object shared by different parts of the program. The Singleton pattern disables all other means of creating objects of a class except for the special creation method.
Yes, in most cases you don't need this complexity, and would just do
var singleton = {
someMethod: function() {}
};
However, the pattern with that getSingleton
function does have one advantage: The object is only constructed when the function is called (for the first time), not before the object is actually needed. Depending on the complexity of the object, this can improve memory usage and startup time of your program. It's basically lazy-loading the module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With