Simple implementation of a Singleton Design Pattern in ES2016
Last active
March 4, 2024 09:01
-
-
Save ilfroloff/76fa55d041b6a1cd2dbe to your computer and use it in GitHub Desktop.
JavaScript Singleton using class
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
'use strict'; | |
import Singleton from 'Singleton'; | |
class ClassA extends Singleton { | |
constructor() { | |
super(); | |
} | |
singletonMethod1() { | |
// ... | |
} | |
singletonMethod2() { | |
// ... | |
} | |
// ... | |
} | |
console.log( | |
ClassA.instance === ClassA.instance, | |
ClassA.instance === new ClassA, | |
new ClassA === new ClassA | |
); // true, true, true |
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
'use strict'; | |
const singleton = Symbol('singleton'); | |
export default class Singleton { | |
static get instance() { | |
if(!this[singleton]) { | |
this[singleton] = new this; | |
} | |
return this[singleton]; | |
} | |
constructor() { | |
let Class = new.target; // or this.constructor | |
if(!Class[singleton]) { | |
Class[singleton] = this; | |
} | |
return Class[singleton]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment