python 设计模式之单例模式

单例模式主要为web中应用的配置文件或模块在实例化的过程中
防止反复加载导致资源浪费.

class Foo(object):
	#实例化一个私有成员属性
    __instance = None  
    def __init__(self):
    	#判断是否是第一次初始化 如果不是 直接return结束
        if self.__instance:
        	return
        else:
            self.name='aa'  
    @classmethod  #类方法
    #判断是否是第一次初始化对象 如果不是 直接return该对象
    def getinstance(cls):
        if cls.__instance == None:
            cls.__instance = Foo()
        return cls.__instance
if __name__ == '__main__':
    foo1 = Foo.getinstance()
    foo2 = Foo.getinstance()
    #判断foo1.name 是否是 foo2.name  返回True
    print(foo1.name is foo2.name)

猜你喜欢

转载自blog.csdn.net/weixin_44222183/article/details/87567286
今日推荐