Created
August 7, 2019 01:51
-
-
Save ctsstc/7a18e5bc91643dc3c504e073a4b55b4b to your computer and use it in GitHub Desktop.
Only allow a singleton instance of a class, no matter who imports it.
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
class SomeClass { | |
constructor() { | |
// Does work 💪 | |
// Maybe this is closer to an injection pattern | |
// Should have a way to remove the inject with a proper interface... | |
} | |
} | |
// Singleton IIFE | |
// Only allow this class to instantiate once, no matter how many times it is included. | |
export default (Singletonizer)(SomeClass); |
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
const instances = {}; | |
const Singletonizer = (Klass, ...args) => { | |
const className = Klass.constructor.name; | |
const created = instances.hasOwnProperty(className); | |
if (!created) { | |
new Klass(...args); | |
instances[className] = true; | |
} | |
} | |
export default Singletonizer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment