Last active
February 3, 2017 20:49
-
-
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.
This file contains hidden or 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
/** | |
* 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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.