PythonでSingleton
GOFデザインパターンにSingletonパターンというものがありますが、これをC#で実装するとこんな感じになります。
class Singleton { private static _singleton = null; public static Singleton getSingleton() { if (Singleton._singleton == null) { Singleton._singleton = new Singleton(); } return Singleton._singleton; } private Singleton() { } } ・・・ // 使い方 int main() { test = Singleton.getSingleton(); return 0; }
では、これをPythonで実装しようと思ったらどうなるか? ということでこんな感じで実装してみました。
class Singleton: _instance = None def __init__(self): raise RuntimeError, "This class cannot be instantiated." def __init_impl__(self): # 初期化処理 pass @staticmethod def get_singleton(): if not Singleton._instance: class _Singleton(Singleton): def __init__(self): self.__init_impl__() Singleton._instance = _Singleton() return Singleton._instance # 使い方 test = Singleton.get_singleton()
Pythonにはpublic, privateの違いがないので、無理矢理Singletonクラスを初期化できないようにしています。でもPythonの流儀からすると、わざわざこんな面倒くさいことせずに、使う側がインスタンスを生成しないようにするべきなんですかね。