Singletons in JavaScript and ES6
The Java way
The first one I learned and the most used design pattern during my Java days was singleton. Writing this in JavaScript is even more simpler.
export const createSingleton = (createInstance) => {
let instance = undefined; return {
getInstance: () => instance || (instance = createInstance())
};
};
This factory requires you to pass in a no argument function that returns a new object. This object becomes the instance value. It also is lazy. Nothing is created until you reference it.
const createSecretId = () => ({ secret: () => "shhhhh" });
const secretId = createSingleton(createSecretId);
console.log(secretId.getInstance().secret());
if you want to be truly semantic, you can use JavaScript generators instead.
const createSingleton = function*(createInstance) {
let instance = undefined;
yield {
getInstance: () => instance || (instance = createInstance())
};
};
The ES6 Way — modules
ES6 Modules are singletons. Thus all you have to do is define your object in a module. To test, you can try:
const phrase = `${Math.random()} shhh`;
export const secret = () => phrase;
Any file you import secret, you are guaranteed to receive the same value. Math.random() is there to tell you if a new value is computed each time.
Code Sandbox: https://codesandbox.io/s/es6-singletons-gwrv3