Skip to content

Instantly share code, notes, and snippets.

@jmcmaster
Last active April 9, 2018 16:56
Show Gist options
  • Save jmcmaster/e2f4539311a294bc3383fad62ddc924e to your computer and use it in GitHub Desktop.
Save jmcmaster/e2f4539311a294bc3383fad62ddc924e to your computer and use it in GitHub Desktop.
// Singleton Pattern
// Inspired by: https://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript
var mySingleton = (function () {
// Instance stores a reference to the Singleton
let instance;
function init() {
// Singleton
// Private methods and variables
function privateMethod(){
console.log( "I am private" );
}
const privateVariable = "Im also private";
const privateRandomNumber = Math.random();
const publicAPI = {
// Public methods and variables
publicMethod: function () {
console.log( "The public can see me!" );
},
publicProperty: "I am also public",
getRandomNumber: function() {
return privateRandomNumber;
}
};
return publicAPI;
};
const mySingletonPublicAPI = {
// Get the Singleton instance if one exists
// or create one if it doesn't
getInstance: function () {
if ( !instance ) {
instance = init();
}
return instance;
}
};
return mySingletonPublicAPI;
})();
// Usage:
var singleA = mySingleton.getInstance();
var singleB = mySingleton.getInstance();
console.log( singleA.getRandomNumber() === singleB.getRandomNumber() ); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment