Last active
November 15, 2016 02:29
-
-
Save neilvoss/2925dd2a4304d3d9161ed6fbae3e73d3 to your computer and use it in GitHub Desktop.
ES6 Singleton
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
// 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sketch pad for Singleton implementations in ES6 JS
I still find this general pattern useful.