🙄

Singletonパターン

2023/07/05に公開

背景

ブロックチェーン関係のエンジニアの方とお話ししていて、Singletonパターンの話が出てきて、知らなかったのでまとめました。

Singletonパターン

https://ja.wikipedia.org/wiki/Singleton_パターン
Singletonパターンについて書かれている記事を置いておきます。

読んだ知識を要約すると"あるクラスのインスタンスが1つしか生成されないようにする"ものと解釈してます。

https://zenn.dev/morinokami/books/learning-patterns-1/viewer/singleton-pattern
具体的な実装としては上記の記事に載っていました。
以下に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