Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save VincentDebug/5e303dd7ae350964ad42735e848d6c37 to your computer and use it in GitHub Desktop.
Save VincentDebug/5e303dd7ae350964ad42735e848d6c37 to your computer and use it in GitHub Desktop.
Creating A True Singleton In Node.js, With ES6 Symbols
// https://derickbailey.com/2016/03/09/creating-a-true-singleton-in-node-js-with-es6-symbols/
// create a unique, global symbol name
// -----------------------------------
const FOO_KEY = Symbol.for("My.App.Namespace.foo");
// check if the global object has this symbol
// add it if it does not have the symbol, yet
// ------------------------------------------
var globalSymbols = Object.getOwnPropertySymbols(global);
var hasFoo = (globalSymbols.indexOf(FOO_KEY) > -1);
if (!hasFoo){
global[FOO_KEY] = {
foo: "bar"
};
}
// define the singleton API
// ------------------------
var singleton = {};
Object.defineProperty(singleton, "instance", {
get: function(){
return global[FOO_KEY];
}
});
// ensure the API is never changed
// -------------------------------
Object.freeze(singleton);
// export the singleton API only
// -----------------------------
module.exports = singleton;
class SingletonDefaultExportInstance {
constructor() {
this._type = 'SingletonDefaultExportInstance';
}
singletonMethod() {
return 'singletonMethod';
}
static staticMethod() {
return 'staticMethod';
}
get type() {
return this._type;
}
set type(value) {
this._type = value;
}
}
export default new SingletonDefaultExportInstance();
// ...
// index.js
import SingletonDefaultExportInstance from './SingletonDefaultExportInstance';
// Instantiate
// console.log(new SingletonDefaultExportInstance); // is not a constructor
// Prototype Method
console.log(SingletonDefaultExportInstance.type, SingletonDefaultExportInstance.singletonMethod());
// Getter/Setter
SingletonDefaultExportInstance.type = 'type updated';
console.log(SingletonDefaultExportInstance.type);
// Static method
console.log(SingletonDefaultExportInstance.constructor.staticMethod());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment