python 设计模式

单例模式

文章暂存

systemime
2020-05-17
1 min

python单例模式实现

# 在实例化时控制检查

class Logger(object):
    _instance = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance  = super(Logger, cls).__new__(cls, *args, **kwargs)
        return cls._instance


log1 = Logger()
log2 = Logger()
print(log1 is log2)

# 通过装饰器实现

from functools import wraps


def singleton(cls):
    __instances = {}

    @wraps(cls)
    def wrapper(*args, **kwargs):
        if cls not in __instances:
            __instances[cls] = cls(*args, **kwargs)
        return __instances[cls]
    return wrapper

@singleton
class Loo(object):
    pass

log1 = Loo()
log2 = Loo()
print(log1 is log2)

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class Logg(metaclass=Singleton):
    pass

log1 = Logg()
log2 = Logg()
print(log1 is log2)

上次编辑于: 5/24/2021, 5:55:49 AM