Created
August 23, 2013 17:22
-
-
Save ankurshukla/6321828 to your computer and use it in GitHub Desktop.
Singleton Pattern in JavaScript
Going over the though process of implementing the same, with a minimal to an optimized route
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/************************************************* | |
* SINGLETON PATTERN IMPLEMENTATION * | |
*************************************************/ | |
//since there are no classes in javascript, every object is technically a singleton | |
//if you don't inherit from it or copy from it. | |
var single = {}; | |
//Singleton Implementations | |
//Declaring as a Global Object...you are being judged! | |
var Logger = function() { | |
//global_log is/will be defined in GLOBAL scope here | |
if(typeof global_log === 'undefined'){ | |
global_log = this; | |
} | |
return global_log; | |
}; | |
//the below 'fix' solves the GLOABL variable problem but | |
//the log_instance is publicly available and thus can be | |
//tampered with. | |
function Logger() { | |
if(typeof Logger.log_instance === 'undefined'){ | |
Logger.log_instance = this; | |
} | |
return Logger.log_instance; | |
}; | |
//the correct way to do it to give it a closure! | |
function logFactory() { | |
var log_instance; //private instance | |
var _initLog = function() { //private init method | |
log_instance = 'initialized'; | |
console.log("logger initialized!") | |
} | |
return { | |
getLog : function(){ //the 'privileged' method | |
if(typeof log_instance === 'undefined'){ | |
_initLog(); | |
} | |
return log_instance; | |
} | |
}; | |
} | |
/***** TEST CODE ************************************************ | |
//using the Logger singleton | |
var logger = logFactory();//did i just gave LogFactory a closure? | |
//create an instance of the logger | |
var a = logger.getLog(); | |
//do some work | |
//get another instance of the logger | |
var b = logger.getLog(); | |
//check if the two logger instances are same? | |
console.log(a === b); //true | |
*******************************************************************/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment