Singleton with Python中的子类

时间:2014-01-25 21:46:37

标签: python singleton subclass

最近,我正在考虑如何在Python中实现Singleton模式。如果Singleton类没有子类,则以下代码可以正常工作。

class Singleton(object):
    _instance = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
        return cls._instance

但是,Singleton类可能有子类。

class SingletonSub1(Singleton):
    def __new__(cls, *args, **kwargs):
        return super(SingletonSub1, cls).__new__(cls, *args, **kwargs)

class SingletonSub2(Singleton):
    def __new__(cls, *args, **kwargs):
        return super(SingletonSub1, cls).__new__(cls, *args, **kwargs)

要求是系统中只能有一个实例,即Singleton,SingletonSub1或SingletonSub2。我该如何实现呢?我知道我绝对可以使用模块级变量来保存Singleton对象。但这真是一个糟糕的代码...

1 个答案:

答案 0 :(得分:2)

使用字典来保存每个子类的实例

class Singleton(object):
    _instances = { }

    def __new__(cls, *args, **kwargs):
        if cls._instances.get( cls, None ) is None:
            cls._instances[ cls ] = super(Singleton, cls).__new__(cls, *args, **kwargs)

        return Singleton._instances[ cls ]