单例模式

 

https://www.cnblogs.com/huchong/p/8244279.html

1.简单单实例,注意调用方式Foo.getinstance() 

但存在线程安全问题

class Foo:
    _instance=None
    var=1

    def __init__(self):
        print("new init")
        # Foo.getinstance()
        pass
    @classmethod
    def getinstance(cls):
        if cls._instance:
            print("already exist instance")
            return cls._instance
        else:
            print("new instance")
            cls._instance=Foo()
            return cls._instance


f1=Foo.getinstance()
f2=Foo.getinstance()
f3=Foo.getinstance()

  

2  new方法

 

posted @ 2018-06-26 10:38  EngineTang  阅读(120)  评论(0编辑  收藏  举报