Python单例模式

来源:互联网 发布:photoshop 软件下载 编辑:程序博客网 时间:2024/05/13 23:47

方法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._instances1 = Singleton()s2 = Singleton()assert id(s1) == id(s2)

方法2:

利用模块实现单例模式

方法3:

Borg模式

class Borg:    __shared_state = {}    def __init__(self):        self.__dict__ = self.__shared_state


 

0 0
原创粉丝点击