Last active
August 25, 2021 02:10
-
-
Save iconifyit/a502aeba9facf393a3951edaf53f0c6b to your computer and use it in GitHub Desktop.
Example of how to implement a Singleton pattern in JavaScript.
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
/* | |
* The instance symbol should be defined in the scope | |
* in which you want the singleton to exist. This does | |
* not necessarily mean globally. Just within your | |
* execution context. | |
*/ | |
let instance | |
const Singleton = (() => { | |
const createInstance = () => { | |
console.log('Calling createInstance') | |
return true | |
} | |
return { | |
getInstance: () => { | |
console.log('Call getInstance'); | |
if (instance === undefined) { | |
instance = createInstance() | |
} | |
return instance | |
}, | |
} | |
})() | |
Singleton.getInstance() | |
Singleton.getInstance() | |
Singleton.getInstance() | |
Singleton.getInstance() | |
// Output | |
// Calling createInstance | |
// Call getInstance | |
// Call getInstance | |
// Call getInstance | |
// Call getInstance |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment