Skip to content

Instantly share code, notes, and snippets.

@neilvoss
Last active November 15, 2016 02:29
Show Gist options
  • Save neilvoss/2925dd2a4304d3d9161ed6fbae3e73d3 to your computer and use it in GitHub Desktop.
Save neilvoss/2925dd2a4304d3d9161ed6fbae3e73d3 to your computer and use it in GitHub Desktop.
ES6 Singleton
// Singleton implemented abstractly in a Class
class Singleton {
constructor() {
var instance = ( Singleton._instance !== undefined ) ? Singleton._instance : this;
Singleton._instance = instance;
return instance;
}
static get instance() {
return new Singleton();
}
}
// Singleton as a static factory that mixes-in the instance reference to the target static class
class Singleton {
getInstance( className ) {
if ( !( className.__instance instanceof className ) ) {
// could also check here if member __instance exists and warn/error/etc. if so
className.__instance = new className();
}
return className.__instance;
}
}
// Singleton as a static factory that keeps its own map of instances
class Singleton {
static getInstance( className ) {
if ( !Singleton.instances ) Singleton.instances = {};
if ( !Singleton.instances[ className ] ) {
Singleton.instances[ className ] = new className();
}
return Singleton.instances[ className ];
}
static remove( className ) {
if ( !Singleton.instances || !Singleton.instances[ className ] ) return;
Singleton.instances[ className ] = null;
}
}
@neilvoss
Copy link
Author

neilvoss commented Jun 10, 2016

Sketch pad for Singleton implementations in ES6 JS

I still find this general pattern useful.

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