Python高手之路【十二】面向对象设计模式

时间:2021-05-27 14:27:14

单例模式

单例,顾名思义单个实例。

class Person:
__instance = None
def __init__(self):
pass
@staticmethod
def getInstance():
if Person.__instance:
return Person.__instance
else:
Person.__instance = Person()
return Person.__instance
obj1 = Person.getInstance()
print(obj1)
obj2 = Person.getInstance()
print(obj2)
##################################################
<__main__.Person object at 0x0088A2D0>
<__main__.Person object at 0x0088A2D0>