Python3-单例模式

版权声明:作者:czp 欢迎留言和交流 https://blog.csdn.net/weixin_41836765/article/details/84317093


通过模块调用:

将需要实现单例的类写在模块文件中,然后通过import引入该模块,得到单例对象


使用__new__()方法:

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

使用装饰器:

def singleton(cls):
    instances = {}
    def getinstance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    return getinstance

@singleton
class singleCls(object):
    def foo(self):
        pass

使用元类:

class SingletonMeta(type):
    __instance = None
    def __call__(cls,*args,**kwargs):
        if not cls.__instance:
            cls.__instance = type.__call__(cls,*args,**kwargs)
        return cls.__instance

class myclass(metaclass = SingletonMeta):
    def foo(self):
        pass

猜你喜欢

转载自blog.csdn.net/weixin_41836765/article/details/84317093