单例

装饰器实现

函数装饰器 实现单例

def singleton(cls):
    _instance = {}

    def inner():
        if cls not in _instance:
            _instance[cls] = cls()
        return _instance[cls]
    return inner
    
@singleton
class Cls(object):
    def __init__(self):
        pass

cls1 = Cls()
cls2 = Cls()
print(id(cls1) == id(cls2))
View Code

 类装饰器实现单例

class Singleton(object):
    def __init__(self, cls):
        self._cls = cls
        self._instance = {}

    def __call__(self, *args, **kwargs):
        if self._cls not in self._instance:
            self._instance[self._cls] = self._cls()
        return self._instance[self._cls]


@Singleton
class Cls2():
    pass

c1 = Cls2()
c2 = Cls2()

print(id(c1) == id(c2))
View Code

 _ _new_ _ 实现单例

class Singleton:
    instance = None

    def __new__(cls, *args, **kwargs):
        if cls.instance is None:
            cls.instance = object.__new__(cls)
        return cls.instance


c1 = Singleton()
c2 = Singleton()

print(id(c1) == id(c2))
View Code

 元类实现

class SingletonMetaclass(type):
    _instance = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instance:
            cls._instance[cls] = super().__call__(*args, **kwargs)
        return cls._instance[cls]


class Index(metaclass=SingletonMetaclass):
    pass


c1 = Index()
c2 = Index()

print(id(c1) == id(c2))
View Code

 

posted @ 2024-04-17 09:30  tslam  阅读(7)  评论(0编辑  收藏  举报