Singleton design patterns ensures a class has only one instance and provide a global point to access it. Singleton pattern is handy when you want to create a class whose functionality does not required any changes for its multiple instances.
Basic Singleton implementation in JavaScript
A basic singleton pattern can be created using simple object literal, because the created object itself will be an instance.
var singleTon = { name: "Reality On Web", location: "Delhi", getInfo: function() { console.log(singleTon.name); console.log(singleTon.location); } }
Above example is very simple and easy to implement, but it is very limited as we cannot have private members in the object.
Singleton implementation with private members in the object
There are many ways of creating singleton design pattern. Depending on your specific need, If you don’t need private member then go with object literal approach.
var myObject = { }; // Singleton is done as in the above example
But to have a private members, it is required to create a class and then expose a method within the class which always returns the same instance.
There are no classes in javascript. But, function can behave like a class in JavaScript.
A very simple singleton pattern implementation
var singleton = new (function() { var bar = 3; this.foo = function() { // whatever } })()
Here, we have just created a self invoking function using the new keywords, that contains private and public data members.
Other way of implementing singleton pattern
var singleTon = (function() { var privateVar = ''; function privateMethod () { // ... } return { // this is your public interface publicMethod1: function () { // all private members are accessible here }, publicMethod2: function () { // all private members are accessible here } }; })();
Leave a Reply