mardi 5 mai 2020

Do singleton's have advantages over modules in typescript?

I've used node/javascript for a few years and am now just getting familiar with typescript. I'm trying to wrap my head around when to use a class and when to use a module in typescript.

In javascript, I would often create modules like this:

const name = "batman";

function getName() {
  return name;
}

module.exports = {
  name
};

In typescript this same code can be written as:

const name: string = "batman";

export function getName(): string {
  return name;
}

However, in reading online, there are a fair amount of examples of singleton's in typescript. I could also write this code as a singleton class like this:

export default class Singleton {
    private static instance: Singleton;
    private name: string = "batman";

    private constructor() { }

    public static getInstance(): Singleton {
        if (!Singleton.instance) {
            Singleton.instance = new Singleton();
        }

        return Singleton.instance;
    }

    public getName() {
        return this.name;
    }
}

I'm struggling to see why I would ever create a singleton as the module is less code and arguably simpler. It also only exists as a single instance. Are there benefits that the singleton offers?

Aucun commentaire:

Enregistrer un commentaire