Last updated on February 28, 2020
In this post, I cover the basic design pattern which all developers will use in their projects knowing or unknowingly.
At least once in a while, we have encountered a situation to create only one instance of an object across the application life span. To achieve this, we have a Singleton pattern in Javascript.
Singleton pattern - Only one instance must be created during app's run time. Which comes under the creational design pattern of GOF(Gang of four).
I give you a code snippet to get a clear picture of the same.
(function () {
var instance;
Tick = function Tick() {
if (instance) {
return instance;
}
};
instance = new Tick();
instance.constructor = Tick;
var value = 0;
instance.getCount = function() {
return value;
};
instance.incCount = function() {
value = value + 1;
}
}());
After running the above code snippet in the chrome console, got the result as below.
Here I used Immediately Invoked Function Expression (IIFE) to achieve this pattern, the advantage of writing this way is our Tick instance properties will not be exposed directly to the global namespace.
If any feedback or comments you have, post it in the comments section. We can improve ourselves by educating each other in a better manner.