🙄
Singletonパターン
背景
ブロックチェーン関係のエンジニアの方とお話ししていて、Singletonパターンの話が出てきて、知らなかったのでまとめました。
Singletonパターン
Singletonパターンについて書かれている記事を置いておきます。
読んだ知識を要約すると"あるクラスのインスタンスが1つしか生成されないようにする"ものと解釈してます。
以下にSingletonの実装コードを引用します。
singleton.js
let instance;
let counter;
class Counter {
constructor () {
if (instance) {
throw new Error ("すでにインスタンスあるぞ!");
}
instance = this;
}
getInstance () {
return this;
}
getCount () {
return counter;
}
increment () {
return counter++;
}
decrement () {
return counter--;
}
}
const counter1 = new Counter();
const counter2 = new Counter();
// counter2の段階で"すでにインスタンスがあるぞ!"というエラーが返ってくる。
Discussion