LoginSignup
0
0

More than 1 year has passed since last update.

Singleton の使用例

Last updated at Posted at 2021-09-25
関連記事のトップページ
[シリーズ] Python におけるデザインパターンの記録

概要

個人的には、Python での Singleton の使用頻度は非常に高い.

が、下記 URL にあるように Singleton の実装方法は何通りもあり、
どれが適切なのかが分からない.

https://try2explore.com/questions/jp/10006686
https://try2explore.com/questions/jp/10158296

私は次のように "静的"変数である __share_state を使う実装を拝借させてもらっている.1

class Singleton(object):
  _share_state = {}
  def __new__(cls, *args, **kwargs):
    obj = super().__new__(cls, *args, **kwargs)
    # "静的"変数 _share_state へのポインタを obj.__dict__ に格納する
    obj.__dict__ = cls._share_state
    # obj を __init__(self) へ渡す
    return obj

class KlassA(Singleton):
  def __init__(self):
    # Singleton クラスの "静的"変数 _share_state に書き込まれる
    self.name = ''
    self.age  = 0

if __name == '__main__':

  a = KlassA
  a.name = 'Qiita'
  a.age  = 10

なお、参考情報として、pypattyrn という Singleton, Decorator, Iterator, Observer などの
デザインパターンを提供するサードパーティパッケージでは次のような実装であった.

class Singleton(type):
    """
    Singleton Metaclass.

    Enforces any object using this metaclass to only create a single instance.

    - External Usage documentation: U{https://github.com/tylerlaberge/PyPatterns/wiki/Creational-Pattern-Usage}
    - External Singleton Pattern documentation: U{https://en.wikipedia.org/wiki/Singleton_pattern}
    """
    __instance = None

    def __call__(cls, *args, **kwargs):
        """
        Override the __call__ method to make sure only one instance is created.
        """
        if cls.__instance is None:
            cls.__instance = type.__call__(cls, *args, **kwargs)

        return cls.__instance

 

以上.


  1. __new__(), __init__(), __dict__ の機構が理解できて、且つ、この方法で都合が悪かったことも無いため 

0
0
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
0
0