【Python3_进阶系列_006】Python3-单例模式

一、单例模式

Python3中常见的实现单例模式的方法有2种:__new__()和装饰器写法

例子:__new__()方法实现单例

class Singleton():
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls,'instance'):
            cls.instance=super().__new__(cls)
        return cls.instance

s1=Singleton()
s2=Singleton()

print(s1==s2)

输出:True

例子2:装饰器实现

def singleton(cls,*args,**kwargs):
    instance={} #空dict
    def get_instance():
        if cls not in instance:
            instance[cls]=cls(*args,**kwargs)
        return instance[cls]
    return get_instance

@singleton
class Apple(): pass

apple1 = Apple()
apple2 = Apple()
apple3 = Apple()
print(id(apple1))
print(id(apple2))
print(id(apple3))

43807472
43807472
43807472

posted @ 2018-07-22 15:21  爱寂寞撒的谎言  阅读(251)  评论(0)    收藏  举报