Python单例模式

方法1:

class Singleton(object):
    _instance = None

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

        return cls._instance

s1 = Singleton()
s2 = Singleton()

assert id(s1) == id(s2)

方法2:

利用模块实现单例模式

方法3:

Borg模式

class Borg:
    __shared_state = {}

    def __init__(self):
        self.__dict__ = self.__shared_state


 

你可能感兴趣的:(Python单例模式)