LoginSignup
23
23

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