Python单例模式实现详解:从基础到多线程安全
本文系统总结Python中单例模式的四种实现方式,包括文件级、类级、基于__new__方法以及基于metaclass元类的方式。重点解析多线程环境下的单例实现,通过双重检查锁定机制解决竞态条件,确保对象唯一性。
一、单例模式
单例模式的实现方式主要包含四种:文件级单例、类级单例、基于__new__方法实现的单例,以及基于metaclass(元类)方式实现的单例。
以下是使用类实现单例模式的具体代码示例:
class Sigletion(objects):
import time
def __init__(self):
time.sleep(1)
@classmethod
def instance(cls,*args,**kwargs)
if not hasattr(Sigletion,'_instance'):
Sigletion._instance=Sigletion(*args,**kwargs)
return Sigletion._instance
import threading
daf task(arg):
obj=Sigletion.instance()
print(obj)
for i in range(10):
t=threading.Thread(target=task,args=[i,])
t.start()
接下来介绍基于__new__方法实现单例模式的方式。
import time
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,*args,**kwargs)
return Singleton._instance
obj1=Singleton()
obj2=Singleton()
print(obj1,obj2)
def task(arg):
obj = Singleton()
print(obj)
for i in range(10):
t = threading.Thread(target=task,args=[i,])
t.start()
最后探讨基于metaclass方式实现单例模式的方案。
理解对象与类的创建机制至关重要: 1. 对象由类创建,在实例化对象时,类的__init__方法会自动执行;当调用对象()时,则执行类的__call__方法。 2. 类由type创建,在定义类时,type的__init__方法会自动执行;当调用类()时,则执行type的__call__方法,该方法内部依次调用类的__new__方法和__init__方法。
# 第0步: 执行type的 __init__ 方法【类是type的对象】
class Foo:
def __init__(self):
pass
def __call__(self, *args, **kwargs):
pass
# 第1步: 执行type的 __call__ 方法
# 1.1 调用 Foo类(是type的对象)的 __new__方法,用于创建对象。
# 1.2 调用 Foo类(是type的对象)的 __init__方法,用于对对象初始化。
obj = Foo()
# 第2步:执行Foodef __call__ 方法
obj()
"""
import threading
class SingletonType(type):
_instace_lock=threading.Lock()
def __call__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
with SingletonType._instace_lock:
if not hasattr(cls, "_instance"):
cls._instance = super(SingletonType,cls).__call__(*args, **kwargs)
return cls._instance
class Foo(metaclass=SingletonType):
def __init__(self,name):
self.name=name
obj1 = Foo('name')
obj2 = Foo('name')
print(obj1,obj2)
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













