python实现单例模式的几种方式

2020-01-08  本文已影响0人  aport

特点:确保某一个类只有一个实例对象

def SingleTon(cls, *args, **kwargs):
    _instance = {}

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


@SingleTon
class A(object):
    a = 1


t1 = A()
print(id(t1))  # 915018585536
t2 = A()
print(id(t2))  # 915018585536
class SingleTon(object):
    _isinstance = None

    def __new__(cls, *args, **kwargs):
        if not cls._isinstance:
            cls._isinstance = super(SingleTon, cls).__new__(cls, *args, **kwargs)
        return cls._isinstance


t1 = SingleTon()
print(id(t1))  # 744789979936
t2 = SingleTon()
print(id(t2))  # 744789979936
上一篇下一篇

猜你喜欢

热点阅读