python——设计模式

单例模式:
某个类中只有一个实例(对象)

class Foo:
    instance = None
    def __init__(self,name):
        self.name = name

    @classmethod    #类方法
    def get_instance(cls):  #cls类名
        if cls.instance:
            return cls.instance
        else:
            obj=cls('alex')
            cls.instance = obj
            return obj

obj1 = Foo.get_instance()
print(obj1)
obj2 = Foo.get_instance()
print(obj2)

 

posted @ 2017-07-17 09:02  沄持的学习记录  阅读(150)  评论(0编辑  收藏  举报