Singleton 1.0.4
Purpose
Singleton
is an implementation of the Singleton Design patternOrigin While looking for examples of Singleton Design pattern, I found these useful clues:
- Usage of
Symbol()
as a way to ensure that theconstructor
will only accept a predefined and unique value - Check that Instance count is less than or equal to One
Then I used a Static Getter for
This
to get the Singleton, so the code to get the Singleton Instance isSingleton.This
(instead of the more common static methodGetInstance()
which in my opinion makes the code too verbous).For targeting all module types, I provided the
CJS
(CommonJS),ES6
(ECMAScript 2015) andUMD
(Universal Module Definition) versions. The conversions (fromCJS
) were performed with the help of therollup
bundler (cjs to es6 and umd.txt
indoc
folder explains how to userollup
for this purpose).The default export (
main
field inpackage.json
) isindex.js
, theES6
version.- Usage of
Source code
`
class Singleton { static #Key = Symbol(); static #Instance = new Singleton( this.#Key ); static #InstanceCount = 0;// ** Private constructor ** constructor( key ) {
if ( key !== Singleton.#_Key ) { throw new TypeError("'Singleton' constructor is private"); } this.name = "Singleton";
} // ** Private constructor ** 'Singleton' design pattern
static get This() {
if ( Singleton.#_Instance == undefined ) { this.#_Instance = new Singleton(); if ( this.#_InstanceCount > 0 ) { throw new TypeError("'Singleton' constructor called more than once"); } this.#_InstanceCount++; } return Singleton.#_Instance;
} // Singleton get 'This'
} // Singleton class
Singleton.This; // NB: ensures that #_InstanceCount = 1`