使用修饰器来实现单例模式

版权声明:版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010412719/article/details/47089883 https://blog.csdn.net/weixin_42139375/article/details/82760162

         许多小伙伴面试的时候,会被频繁的问道手写单例模式,尤其是再加上装饰器,就更晕了。下面听过一串代码来实现,仅供参考。如有错误,敬请指正!

def Singleton(cls):
    instances = {}

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

    return get_instance

猜你喜欢

转载自blog.csdn.net/weixin_42139375/article/details/82760162