Singletonパターンをpython2.6で書いてみた。
初回のみインスタンス生成する。
この部分が、マルチスレッドではうまくいかないかもしれない?
(複数のスレッドから同時アクセスしたいなら、あらかじめ生成しておくべきか)
# -*- coding: utf-8 -*- class Senario(object): # これがsingletonなクラス。某エロゲ会社を想定。 __writer = None def __new__(cls): return object.__new__(cls) @classmethod def get_instance(cls): # 実体を取得します。 if cls.__writer is None: cls.__writer = cls() return cls.__writer # シナリオライターを返却。 instance = property(get_instance) if __name__ == "__main__": (abisubouto, darekare) = (None, None) # 2本のソフトがあります abisubouto = Senario.instance # シナリオ取得その1 darekare = Senario.instance # シナリオ取得その2 # この時点で、阿鼻巣暴徒==誰彼が成立します。 if abisubouto is darekare: print("同じ") else: print("違う") assert abisubouto is darekare
__metaclass__を使う方法もあるようだ。
実用するならこっちのがいいかも。
# -*- coding: utf-8 -*- class Singleton(type): ''' 以下のサイトで紹介されている実現方法を参考にした。 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/412551Python で Singleton/シングルトン パターン''' def __init__(self, *args): type.__init__(self, *args) self._instance = None def __call__(self, *args): if self._instance is None: self._instance = type.__call__(self, *args) return self._instance class Senario(object): # これがsingletonなクラス。某エロゲ会社を想定。 __metaclass__ = Singleton # このクラスをSingletonベースにする意味? def __init__(self, *args): self.__writer = "chou sensei" def get_instance(self): return self.__writer instance = property(get_instance) if __name__ == "__main__": (abisubouto, darekare) = (None, None) # 2本のソフトがあります abisubouto = Senario().instance # シナリオ取得その1 darekare = Senario().instance # シナリオ取得その2 # この時点で、阿鼻巣暴徒==誰彼が成立します。 if abisubouto is darekare: print("同じ") else: print("違う") assert abisubouto is darekare
参考にしたサイト:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/412551
http://memo.jj-net.jp/154