Skip to content

Instantly share code, notes, and snippets.

@kimmellj
Created March 18, 2015 19:04
Show Gist options
  • Save kimmellj/92d8c231de8d4d682deb to your computer and use it in GitHub Desktop.
Save kimmellj/92d8c231de8d4d682deb to your computer and use it in GitHub Desktop.
Configuration Singleton Example - JavaScript
/**
* http://robdodson.me/javascript-design-patterns-singleton/
* http://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript
*/
var Configuration = (function () {
// Instance stores a reference to the Singleton
var instance;
function init() {
// Singleton
// Private methods and variables
function loadConfig(){
console.log( "Loading Config ..." );
}
function saveConfig(){
console.log( "Saving Config ..." );
}
function createConfig(){
console.log( "Creating Config ..." );
}
var refreshInterval = 999; //Set with a default value
loadConfig();
return {
// Public methods and variables
getRefreshInterval: function () {
console.log( "Getting Refresh Interval" );
return refreshInterval;
},
setRefreshInterval: function (refreshIntervalParam) {
console.log( "Setting Refresh Interval" );
refreshInterval = refreshIntervalParam;
saveConfig();
}
/**
* @todo add the other getters and setters
*/
};
};
return {
// Get the Singleton instance if one exists
// or create one if it doesn't
getInstance: function () {
if ( !instance ) {
instance = init();
}
return instance;
}
};
})();
// Usage:
var singleA = Configuration.getInstance();
var singleB = Configuration.getInstance();
console.log( "Are the two instances the same? " + (singleA === singleB) ); // true
Configuration.getInstance().setRefreshInterval(2000);
console.log("Refresh Interval is: " + Configuration.getInstance().getRefreshInterval());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment