LoginSignup
5
6

More than 3 years have passed since last update.

Singletonパターン Python実装 メモ

Posted at
  • Pythonとデザインパターンの学習記録。今回はSingletonパターンについてメモする。

Singleton パターンとは

  • デザインパターンの1つ。
  • オブジェクト指向では、一般的に1つのクラスから複数のインスタンスを作成することができる。
  • Singletonはアプリケーション全体でインスタンスを1つしか生成されないよう保証する仕組みを指す。

クラス図と条件

singleton_pattern.png

  1. 同じ型のインスタンスをprivate なクラス変数として定義する。

  2. コンストラクタの可視性をprivateとする。

  3. 同じ型の同じ型のインスタンスを返す getInstance() クラスメソッドを定義する。

Wikiより

サンプルプログラム

  • singleton.py

※スレッド制御は未考慮。

class Singleton:

    # 条件1. 同じ型のインスタンスをprivate なクラス変数として定義する。
    ## 1インスタンスしか生成しないことを保証するために利用する。
    _unique_instance = None

    # 条件2. コンストラクタの可視性をprivateとする。
    ## pythonの場合、コンストラクタをprivate定義できない。
    ## コンストラクタ呼び出しさせず、インスタンス取得をget_instanceに限定する。
    ## get_instanceからインスタンス取得を可能にするため、__init__は使用しない。
    ## 初期化時に、__new__が__init__よりも先に呼び出される。
    def __new__(cls):
        raise NotImplementedError('Cannot Generate Instance By Constructor')

    # インスタンス生成
    @classmethod
    def __internal_new__(cls):
        return super().__new__(cls)

    # 条件3:同じ型のインスタンスを返す `getInstance()` クラスメソッドを定義する。
    @classmethod
    def get_instance(cls):
        # インスタンス未生成の場合
        if not cls._unique_instance:
            cls._unique_instance = cls.__internal_new__()
        return cls._unique_instance


if __name__ == '__main__':
    ins1 = Singleton.get_instance()
    print(ins1)
    ins2 = Singleton.get_instance()
    print(ins2)
    # 同一インスタンスであることの確認
    print(ins1 == ins2)

動作確認

python singleton.py
<__main__.Singleton object at 0x00000292A08B31C0>
<__main__.Singleton object at 0x00000292A08B31C0>
True

参考情報

5
6
0

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
5
6