-
-
Save YozhEzhi/3d4d12c2e6cd38427e1eefda94517c6b to your computer and use it in GitHub Desktop.
ES6 singleton pattern: constructor returns an instance scoped to the module. Without using the `new` operator.
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
const singleton = Symbol(); | |
const singletonEnforcer = Symbol(); | |
class Singleton { | |
constructor(enforcer) { | |
if (enforcer !== singletonEnforcer) { | |
throw new Error('Cannot construct singleton'); | |
} | |
this._type = 'Singleton'; | |
} | |
static get instance() { | |
if (!this[singleton]) { | |
this[singleton] = new Singleton(singletonEnforcer); | |
} | |
return this[singleton]; | |
} | |
singletonMethod() { | |
return 'singletonMethod'; | |
} | |
static staticMethod() { | |
return 'staticMethod'; | |
} | |
get type() { | |
return this._type; | |
} | |
set type(value) { | |
this._type = value; | |
} | |
} | |
export default Singleton; | |
// index.js | |
import Singleton from './Singleton'; | |
// Instantiate | |
// console.log(new Singleton); // => Cannot construct singleton | |
// Instance | |
const instance2 = Singleton.instance; | |
// Prototype Method | |
console.log(instance2.type, instance2.singletonMethod()); | |
// Getter/Setter | |
instance2.type = 'type updated'; | |
console.log(instance2.type); | |
// Static method | |
console.log(Singleton.staticMethod()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment