Singletonパターン (3) - モジュール
- Singletonパターン (1)
- Singletonパターン (2) - ぜ〜んぶクラスメソッド
- Singletonパターン (3) - モジュール
- Singletonパターン (4) - メタクラスを使った方法
- Singletonパターン (5) - Borgの方法
実はPythonには、どんなクラスも簡単にSingleton化する方法があったのです!
class FooBar(object): pass FooBar = FooBar()
これで、FooBarのインスタンスは作れません(笑い)
もちろん、この簡単Singletonを突破するのは簡単です。
import copy
e2 = copy.copy(FooBar)
でも、Pythonを使っている限り、
どんなに凝ったSingletonを作っても無駄です。
例えばSingletonパターン (1)
のSingletonも簡単に突破できます。
#いわゆるSingleton class Singleton(object): _instance = None def __new__(cls, *a, **kw): if cls._instance is None: cls._instance = object.__new__(cls, *a, **kw) return cls._instance def set_name(self, name): self.name = name def get_name(self): return self.name s1 = Singleton() s1.set_name("foo") Singleton._instance = None s2 = Singleton() s2.set_name("bar") print s1.get_name(), s2.get_name() #=> foo bar
また、モジュールを使う方法もあります。
モジュールは1つしか存在しません。グローバル変数と普通の関数を定義したモジュールは、Singletonになります。
また、普通のクラスをモジュールを使ってSingleton化する事もできます。
#module_singleton.py class _Example(object): def set_name(self, name): self.name = name def get_name(self): return self.name _instance = _Example() set_name = _instance.set_name get_name = _instance.get_name if __name__ == "__main__": import module_singleton module_singleton.set_name("asopasomaso") print(module_singleton.get_name())