python中单例模式的实现-通过闭包函数和魔术方法__new__实现单例模式

chongtianfeiyu 2020-01-06

1、通过闭包函数实现单例模式:

# 使用闭包函数实现单例
def single(cls, *args, **kwargs):
    instance = {}

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


@single
class Apple:
    pass


a = Apple()
b = Apple()
print(id(a))
print(id(b))

2、通过python中魔术方法__new__实现单例模式:

class Single:
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, ‘_instance‘):
            cls._instance = super(Single, cls).__new__(cls)
        return cls._instance


s1 = Single()
s2 = Single()
print(id(s1))
print(id(s2))

相关推荐