Skip to content

Instantly share code, notes, and snippets.

@munkacsitomi
Last active February 19, 2020 13:16
Show Gist options
  • Save munkacsitomi/5b82bff7e6c73f4b53b4ddaee4da3d49 to your computer and use it in GitHub Desktop.
Save munkacsitomi/5b82bff7e6c73f4b53b4ddaee4da3d49 to your computer and use it in GitHub Desktop.
Singleton Design Pattern in JavaScript
const singleton = (() => {
// Instance stores a reference to the Singleton
let instance;
const init = () => {
// Private methods and variables
const privateMethod = () => {
console.log('Private function');
};
const privateVariable = 'Private variable';
const privateRandomNumber = Math.random();
return {
// Public methods and constiables
publicVariable: 'Public variable',
publicMethod: () => {
console.log('Public function');
},
getRandomNumber: () => {
return privateRandomNumber;
}
};
};
return {
// Get the Singleton instance if one exists
// or create one if it doesn't
getInstance: () => {
if (!instance) {
instance = init();
}
return instance;
}
};
})();
const singletonA = singleton.getInstance();
const singletonB = singleton.getInstance();
console.log('Singleton A:', singletonA.getRandomNumber());
console.log('Singleton B:', singletonB.getRandomNumber());
console.log('isSingleton:', singletonA.getRandomNumber() === singletonB.getRandomNumber()); // isSingleton: true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment