mercredi 28 mars 2018

TypeScript pattern to pass options while creating singleton instance

I have a TypeScript singleton class

Class MySingleton {
    private static _instance: MySingleton;

    private constructor();

    public static getInstance() {
        if (!MySingleton._instance) {
            MySingleton._instance = new MySingleton();
        }

        return MySingleton._instance;
    }

}

Now, I would like to pass some options while creating this singleton instance.

E.g an option that sets the mode of the instance to production mode.

So, that could be implemented by having getInstance accept an options object that gets propagated to the constructor. Then the usage becomes like

MySingleton.getInstance({
    prodMode: true
});

Is this the best way to do this? I feel kind of icky about doing this because when the consumer of MySingleton executes getInstance by passing an options object, there is no way for him or her to know that the passed options object will be used or just disregarded.

Aucun commentaire:

Enregistrer un commentaire