python 三种单例模式

  1. 装饰器

# 装饰器
def singleton(cls):
    instance = {}
    def inner(*args, **kw):
        if cls not in instance:
            instance[cls] = cls(*args, **kw)
        return instance[cls]
    return inner

@singleton
class A:
    pass

a = A()
b = A()

print(a is b)

  1. 元类
# 元类
class Meta(type):
    def __init__(cls, *args, **kwargs):
        super().__init__(*args, **kwargs)
        cls.instance = None

    def __call__(cls, *args, **kwargs):
        if cls.instance is None:
            cls.instance = super(Meta, cls).__call__(*args, **kwargs)
        return cls.instance


class A(metaclass=Meta):  # A 是 meta 的实例
    pass


a = A()  # A() 会调用 meta 的 __call__() 方法
b = A()

print(a is b)


  1. 构造函数

# 构造方法
class Base(object):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            cls._instance = super(Base, cls).__new__(cls)
        return cls._instance

class A(Base):
    pass

a = A()
b = A()

print(a is b)


posted @ 2021-11-08 17:14  wztshine  阅读(93)  评论(0编辑  收藏  举报