Last active
February 19, 2020 13:16
-
-
Save munkacsitomi/5b82bff7e6c73f4b53b4ddaee4da3d49 to your computer and use it in GitHub Desktop.
Singleton Design Pattern in JavaScript
This file contains hidden or 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
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