Skip to content

Instantly share code, notes, and snippets.

@peeke
Last active February 3, 2017 20:49
Show Gist options
  • Save peeke/466b0fe6d1a155594e7b125295c35520 to your computer and use it in GitHub Desktop.
Save peeke/466b0fe6d1a155594e7b125295c35520 to your computer and use it in GitHub Desktop.
Optional singleton pattern: provides a class with a method to retrieve a key based instance.
/**
* Pattern which allows for a class to be optionally instantiated as singleton, using the Foo.getSingleton('foo') method
*/
const instances = new Map();
class Foo {
constructor() {
// Do all kinds of stuff, e.g. keeping state for a page
}
static getSingleton(key = '') {
if (!instances.has(key)) {
instances.set(key, new Foo());
}
return instances.get(key);
}
}
export default Foo;
@peeke
Copy link
Author

peeke commented Feb 3, 2017

const singleton = Foo.getSingleton()
const differentSingleton = Foo.getSingleton('different')
const otherSingleton = Foo.getSingleton('different')
const instance = new Foo();

singleton !== differentSingleton; // true
differentSingleton === otherSingleton; // true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment