Created
June 16, 2014 08:56
-
-
Save quipu/6be09cd7847951722096 to your computer and use it in GitHub Desktop.
Example code demonstrating the singleton design 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
var dom = (function() { | |
var _counter = 0, | |
instance; | |
generateId = function () { | |
return "customId" + _counter; | |
}; | |
create = function (tagName, id) { | |
var el = document.createElement(tagName); | |
el.id = id || generateId(); | |
return el; | |
}; | |
// Create a public function containing all the object functions | |
// we wish to expose | |
function createInstance() { | |
return { | |
generateId : generateId, | |
create : create | |
}; | |
} | |
// Rather than returning public members we return a single | |
// getInstance() function which either creates an | |
// instance of the object | |
// or returns the already created instance, thereby ensuring only one | |
// instance of the object is created. | |
return { | |
getInstance : function() { | |
// return the existing instance or create then send | |
return instance || createInstance(); | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment