Singleton Pattern in JavaScript

In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

In JavaScript this pattern restricts instantiation of an object to a single reference thus reducing its memory footprint and allowing a "delayed" initialization on an as-needed basis. This isn't too common among JavaScript projects.

Here is how a singleton pattern can be implemented with JavaScript

  1. Easiest way is using object literals
    
    var singletonObject ={
        method1:function(){
            
        },
        method2:function(){
        
        }
    }

  2. Little more organized way using closures
    
    var singletonObject = (function(){
        var instance;
        
        function initiateInstance(){
            var object = new Object("my Object");
            return object;
        }
        
        return{
            getSingletonInstance:function(){
                if(!instance){
                    instance=initiateInstance();
                }
                return instance;
            }
        }
        
    })();
    
    
    when we access the object it can be done like,
    
    var instance1=singletonObject.getSingletonInstance();
    var instance2=singletonObject.getSingletonInstance();
    
    //instance1===instance2
    
    

No comments:

Post a Comment