Created
June 15, 2012 04:34
-
-
Save zhuochun/2934678 to your computer and use it in GitHub Desktop.
Singleton JavaScript Pattern
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
// http://kaijaeger.com/articles/the-singleton-design-pattern-in-javascript.html | |
var Singleton = (function() { | |
var instance = null; | |
function PrivateConstructor() { | |
var rand = Math.round(Math.random() * 100); | |
this.getRand = function() { | |
return rand; | |
} | |
} | |
return new function() { | |
this.getInstance = function() { | |
if (instance == null) { | |
instance = new PrivateConstructor(); | |
instance.constructor = null; | |
} | |
return instance; | |
} | |
} | |
})(); | |
var singletonInstance = Singleton.getInstance(); | |
// ============================= | |
// In a remotely aspect oriented kind of way, you could even do this: | |
// ============================= | |
var global = this; | |
function singletonify(constructorName) { | |
var constructorFunc = global[constructorName]; | |
var instance = null; | |
global[constructorName] = new function() { | |
this.getInstance = function() { | |
if (instance == null) { | |
instance = new constructorFunc(); | |
instance.constructor = null; | |
} | |
return instance; | |
} | |
} | |
} | |
function RegularConstructor() { | |
var rand = Math.round(Math.random() * 100); | |
this.getRand = function() { | |
return rand; | |
} | |
} | |
singletonify("RegularConstructor"); | |
var myInstance = RegularConstructor.getInstance(); | |
document.write(myInstance.getRand()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment