Python3-单例模式

Python3-单例模式_第1张图片


通过模块调用:

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

Python3-单例模式_第2张图片


使用__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

 

你可能感兴趣的:(设计模式)