python设计模式之--单例模式

时间:2023-03-09 12:59:33
python设计模式之--单例模式

python的单例模式就是一个类的实例只能自始自终自能创建一次。应用场景比如说数据库的连接池。

#!/usr/bin/env python
# coding=utf- class Foo(object): instance = None def __init__(self, name):
self.name = name @classmethod
def get_instance(cls):
if cls.instance:
return cls.instance
else:
obj = cls('hexm')
cls.instance = obj
return obj obj = Foo.get_instance()
obj1 = Foo.get_instance()
print(obj.name)
print(obj1.name)
print(Foo.instance)
print(obj)