Created
April 11, 2021 19:04
-
-
Save iconifyit/b7b131208bf9534181ae7959070746af to your computer and use it in GitHub Desktop.
JavaScript singleton implementation
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 | |
* outermost execution context. | |
*/ | |
let instance; | |
const Singleton = (() => { | |
const createInstance = () => { | |
const ts = String(new Date().getTime()); | |
console.log('Calling createInstance', ts) | |
return `Instance timestamp : ${ts}` | |
}; | |
return { | |
getInstance: () => { | |
if (instance === undefined) { | |
instance = createInstance(); | |
} | |
return instance; | |
}, | |
}; | |
})(); | |
// This part just tests the above to verify it is a true singleton. | |
let counter = 0; | |
let tid = setInterval(() => { | |
console.log( Singleton.getInstance() ) | |
counter++ | |
if (counter > 5) clearInterval(tid) | |
}, 1000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment