class Foo:
def __init__(self, name, age):
self.name = name
self.age = age
def show(self):
print(self.name, self.age)
v = None
while True:
if v:
v.show()
else:
v = Foo('klvchen', 666)
v.show()
运行结果:
无限循环 666
不需要重复生产对象
class Foo:
__v = None
@classmethod
def get_instance(cls):
if cls.__v:
return cls.__v
else:
cls.__v = Foo()
return cls.__v
obj1 = Foo.get_instance()
print(obj1)
obj2 = Foo.get_instance()
print(obj2)
obj3 = Foo.get_instance()
print(obj3)
运行结果:
<__main__.Foo object at 0x0000029958542518>
<__main__.Foo object at 0x0000029958542518>
<__main__.Foo object at 0x0000029958542518>
单例模式可以很好地保证当前内存中仅存在单个实例,避免内存浪费。