Skip to content

Instantly share code, notes, and snippets.

@ctsstc
Created August 7, 2019 01:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ctsstc/7a18e5bc91643dc3c504e073a4b55b4b to your computer and use it in GitHub Desktop.
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.
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);
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