23
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TypeScriptでSingletonパターンを実装する

Posted at

TypeScriptでSingletonパターンを実装するメモです。
個人的にどの言語でもよく利用する構文です。

class Singleton {
    private static _instance:Singleton = null;
    constructor() {
        if(Singleton._instance){
            throw new Error("must use the getInstance.");
        }
        Singleton._instance = this;
    }
    public static getInstance():Singleton {
        if(Singleton._instance === null) {
            Singleton._instance = new Singleton();
        }
        return Singleton._instance;
    }
}

インスタンス生成はstaticにgetInstanceで。

var singleton=Singleton.getInstance();

もっと良い方法や指摘があれば是非教えて欲しいです。

23
23
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?