JavaScript - An example for Singleton pattern

The singleton pattern is a design pattern that restricts instantiation of the class to one object. This pattern is very handy when one object is enough for doing some operation across the entire system. Let's see an example.

/**
 * Single global namespace for an entire application with lazy loading.
 * @Singleton pattern
 */

var PUS = PUS || {};

PUS = (function(){
 //Private variables and methods
 var appVersion = 0.1,
  instance = null;
 function constructor() {
  console.log('Object has created');
   return {
    getAppVersion : function() {
    return appVersion;
   }
   };
 };
 return {
  getInstance : function() {
   if(!instance) {
    instance = constructor();
   }
   return instance;
  }
 };
})();

Here PUS object contains one public method called "getInstance". If we call PUS. getInstance() method, that will first check whether an object is already created or not. The object is already exists then will return the reference of an existing object, otherwise it will create a new instance and return that instance (Lazy initialization). Sample usage is given below.



Comments

Popular Posts