单例(Singleton)模式就是一个类只能实例化一个对象,这个类必须自己创建自己的唯一实例。
一般情况下,一个类可以实例化多个对象:
p1 = Person("zhangsan",180)
print(p1)
print(p1.name)
p2 = Person("lishi",175)
print(p2)
print(p2.name)
执行结果:
__new__ is called
__init__ is called
<__main__.Person object at 0x000001939679BC88>
zhangsan
__new__ is called
__init__ is called
<__main__.Person object at 0x000001939679BC48>
lishi
发现两个实例化对象的内存地址不一样,单例模式写法:
class Singleton(object):
# 单例模式
_instance = None
def __new__(cls, *args, **kwargs):
print("__new__ is called")
if cls._instance is None:
cls._instance = object.__new__(cls)
return cls._instance
#小编创建了一个Python学习交流群:725638078
def __init__(self,x, y):
print("__init__ is called")
self.name = x
self.height = y
单例模式重写了__ new__
方法,保证只存在一个实例化对象。
执行:
p1 = Singleton("zhangsan",180)
print(p1)
print(p1.name)
p2 = Singleton("lishi", 175)
print(p2)
print(p2.name)
print(p1.name)
输出结果:
__new__ is called
__init__ is called
<__main__.Singleton object at 0x00000243DD386E48>
zhangsan
__new__ is called
__init__ is called
<__main__.Singleton object at 0x00000243DD386E48>
lishi
lishi
两个实例化对象指向了相同的内存地址,单例模式可以保证系统中一个类只有一个实例,如果希望某个类的对象只能存在一个,使用单例模式可以节省内存。