Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right way for Singleton pattern in Typescript/ES6?

class Foo{

}

var instance: Foo;
export function getFooInstance(){
    /* logic */
}

or

export class Foo{
    private static _instance;
    private constructor(){};
    public getInstance(){/* logic */}
}

// Use it like this
Foo.getInstance()

I want to make sure there is only one way instance of the object ? Any other suggestions apart from this ?

Typescript Playground link for both:

like image 375
Harshil Lodhi Avatar asked Dec 10 '22 14:12

Harshil Lodhi


1 Answers

If you want to use the getter in the class then it needs to be static:

export class Foo{
    private static _instance;
    private constructor(){};
    public static getInstance(){/* logic */}
}

The thing is that while the compiler will enforce this private visibility, in runtime it will still be possible to bypass it, even unintentionally, if for example someone uses that from javascript directly.

If you enforce it using a module/namespace then you can completely hide it:

Using a module:

export interface IFoo {}

class Foo implements IFoo {}

var instance: Foo;
export function getFooInstance(): IFoo {
    /* logic */

    return instance;
}

It's your code, I just aded the IFoo interface (which is also exported) so that who ever gets an instance will know the interface but not the class.

Using a namespace:

namespace Foo {
    export interface IFoo {}

    class FooClass implements IFoo {}

    const instance = new FooClass();
    export function getInstance(): IFoo {
        return instance;
    }
}
like image 133
Nitzan Tomer Avatar answered Feb 20 '23 00:02

Nitzan Tomer