简介
顾名思义,单例(singleton)就是只有一个实例。单例模式的要点是:一个类只能有一个实例,这个实例在第一次调用的时候创建,在程序退出的时候销毁。
实现
我们可以利用 Python 的 __new__ 方法轻松实现单例模式。__new__ 方法在 __init__方法之前调用,并且 __init__ 方法的 self 参数就是 __new__ 方法的返回值,其他参数与 __new__ 方法其余的参数一致。闲话少说,请看代码:
import threading
class Singleton(object):
lock = threading.Lock()
# None表示实例还没有创建
instance = None
created = False
def __new__(cls):
print('__new__被调用')
if Singleton.instance == None:
# 加锁是为了线程安全
with Singleton.lock:
if Singleton.instance == None:
print('即将创建instance')
# 这一行很关键
Singleton.instance = super().__new__(cls)
return Singleton.instance
def __init__(self):
# 确保__init__只执行一次
if Singleton.created:
return
print('__init__被调用')
Singleton.created = True
obj1 = Singleton()
obj2 = Singleton()
print(obj1 is obj2)
执行后,输出的结果是:
__new__被调用
即将创建instance
__init__被调用
__new__被调用
True
完美!