samedi 27 octobre 2018

javascript good way to create or design Singleton class

I think in javascript it could create Singleton class like below

test.js
class Container {
    constructor() {
      this.map = new Map;
    }

    set(key, value) {
      this.map.set(key, value);
    }

    get(key) {
      return this.map.get(key);
    }
  }
module.exports.Container = new Container();

so that I could use that other files like in index.js

import container from './test'

However the constructor of Container need some other parameters so that it could do better. And the Container also need to be Singleton class , because it is a common class . And i do not know how to create it?

constructor(servie) {
      this.map = new Map;
      this.servie = servie;
    }

by the way the service variable is created when application starts

Aucun commentaire:

Enregistrer un commentaire