0

I came across following implementation of singleton design pattern in javascript.

var Singleton = (function () {
var instance;

function createInstance() {
    var object = new Object("I am the instance");
    return object;
}

return {
    getInstance: function () {
        if (!instance){
            instance = createInstance();
        }
        return instance;
    }
};
})();

APPROACH TWO

var singleton = (function(){
var a = { value: "string"};

return {
    getInstance: function(){
                   return a;
                 }
 };
})();
var ob = singleton.getInstance();
var be = singleton.getInstance();
console.log(ob===be); //logs true

So My question is are there any issue with second approach.

I think there is no need to create a function and let it return an object, instead we can simply create one object and return it through getInstance() method, and since it is IIFE( immediately invoked function), there is only one instance of the object being created, so we any way do not need to have following check if(!instance){instance = createInstance()} rather we should just have immediately invoked function, create an object in that function, which will be private object and then return it through the getInstance method.

MY QUESTION IS : Am i correct in my understanding Or I am missing some point and thus wrong in my implementation of singular in javascript.

Thank you very much

Akshay Vijay Jain
  • 13,461
  • 8
  • 60
  • 73

2 Answers2

1

The reason this is done

return {
    getInstance: function () {
        if (!instance){
            instance = createInstance();
        }
        return instance;
    }
};

the instance will not be created until getInstance is called the first time ... so the singleton may never be instantiated (good if it's "epensive" to do so)

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
0

Yes Second approach is correct. There is no issues with second approach.

People explain taking use of first approach by extending it from java, which is class based language where we need to instantiate an object before use,

But in javascript we can simply create an object using Object literal and it will be singleton object for example: var a = { }; here a is singleton object, there cannot be another instance of created which is like a.

And if we want our singleton object to have private variables and private methods we can go by the SECOND APPROACH mentioned in the question.

Please see the following links for clarification Simplest/Cleanest way to implement singleton in JavaScript?

javascript singleton question

Community
  • 1
  • 1
Akshay Vijay Jain
  • 13,461
  • 8
  • 60
  • 73