设计模式之十一--单例模式

单例模式:保证一个类只有一个实例,并提供一个访问它的全局访问点。

单例大家应该都知道,这里更多来看一下,python实现单例的一些特性
装饰器来实现的版本

from functools import wraps


def singleton(cls):
    _instance = {}

    @wraps(cls)
    def wrapper():
        if cls not in _instance:
            _instance[cls] = cls()

    return wrapper


@singleton
class Child:
    def __init__(self):
        print("This is the singleton test")

    def play(self):
        print("Please be a happy kid")


if __name__ == "__main__":
    t1 = Child()
    t2 = Child()

    if t1 is t2:
        print("They are the same kid")

重写类的__new__方法

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


if __name__ == "__main__":
    t1 = Singleton()
    t2 = Singleton()

    if t1 is t2:
        print("They are the same thing")

高端版:元类实现。

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 Child(metaclass=Singleton):
    def __init__(self):
        print("This is the singleton test")

    def play(self):
        print("Please be a happy kid")


if __name__ == "__main__":
    t1 = Child()
    t2 = Child()

    if t1 is t2:
        print("They are the same kid")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值