一、单例模式
菜鸟教程-单例模式:https://www.runoob.com/design-pattern/singleton-pattern.html
二、python实现单例模式错误的示范
在网上看到的一个例子是使用双检锁实现单例模式,这个方法通过重载python对象的__new__
方法,使得每个类只能被new一次。代码如下:
import threading
class Singleton(object):
_instance_lock = threading.Lock()
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if not hasattr(Singleton, "_instance"):
with Singleton._instance_lock:
if not hasattr(Singleton, "_instance"):
Singleton._instance = object.__new__(cls)
return Singleton._instance
obj1 = Singleton()
obj2 = Singleton()
print(obj1,obj2)
上面的代码看似实现了单例模式,但是只是实现了一个单例模式的外壳,为什么这么说呢,我们在__init__
函数里加一个打印语句看看。
import threading
class Singleton(object):
_instance_lock