What is the correct path for a 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 that there is only one instance of an object? Any other suggestions besides this?

Typescript Playground link for both:

+4
source share
3 answers

If you want to use getter in a class, then it must be static:

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

The fact is that although the compiler will use this confidential visibility, at run time it will still be possible to bypass it, even unintentionally, if, for example, someone uses it from javascript directly.

If you apply it with a module / namespace, you can completely hide it:

:

export interface IFoo {}

class Foo implements IFoo {}

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

    return instance;
}

, IFoo ( ), - , , .

:

namespace Foo {
    export interface IFoo {}

    class FooClass implements IFoo {}

    const instance = new FooClass();
    export function getInstance(): IFoo {
        return instance;
    }
}
+5

JS , , TypeScript, , w/ , ?

const Foo = {
  doSomething() {

  }
}

export default Foo;

IMO, KISS, , .

, . , .

export function doSomething() {
}

, *. , .

import * as Foo from './Foo';

Foo.doSomething();
+4

, singleton . getInstance , singleton factory:

class Foo {
    private static _instance;
    constructor(...args) {
        if (Foo._instance) {
            return Foo._instance;
        }

        // if Foo extends non-singleton class or whatever,
        // super(...args);

        Foo._instance = this;
    };
}

, :

@singleton
class Foo { ... }

- , < TypeScript, singleton decorator Singleton extends Class:

function singleton(Class) {
    function extend(sub, sup) {

        for (var prop in sup)
            if (sup.hasOwnProperty(prop))
                sub[prop] = sup[prop];

        function __() {
            this.constructor = sub;
        }

        __.prototype = sup.prototype;
        sub.prototype = new __();
    };

    const Singleton = <any>function (...args) {
        if (Singleton._instance) {
            return Singleton._instance;
        }

        Class.apply(this, args);

        Singleton._instance = this;
    }

    extend(Singleton, Class);

    return Singleton;
}

, .

+2

Source: https://habr.com/ru/post/1657865/


All Articles