当前位置: 首页 > 图灵资讯 > 行业资讯> python单例模式是什么意思

python单例模式是什么意思

发布时间:2025-04-06 15:49:22

单例模式(Singleton Pattern)它是一种常用的软件设计模式,其主要目的是确保某一类只有一个例子。当您希望在整个系统中只有一个例子时,单个例子对象可以派上用场。

单例模式

a、单例模式分为文件、类、基于__四种类型new__基于metaclass实现单例模式的方法。

b、类别实现如下:

classSigletion(objects):
importtime
def__init__(self):
time.sleep(1)
@classmethod
definstance(cls,*args,**kwargs)
ifnothasattr(Sigletion,'_instance'):
Sigletion._instance=Sigletion(*args,**kwargs)
returnSigletion._instance

importthreading

daftask(arg):
obj=Sigletion.instance()
print(obj)

foriinrange(10):
t=threading.Thread(target=task,args=[i,])
t.start()

相关推荐:Python免费入门教程

c、基于__new_____________________

importtime
importthreading
classSingleton(object):
_instance_lock=threading.Lock()
def__init__(self):
pass
def__new__(cls,*args,**kwargs):
ifnothasattr(Singleton,"_instance"):
withSingleton._instance_lock:
ifnothasattr(Singleton,"_instance"):
Singleton._instance=object.__new__(cls,*args,**kwargs)
returnSingleton._instance

obj1=Singleton()
obj2=Singleton()
print(obj1,obj2)

deftask(arg):
obj=Singleton()
print(obj)

foriinrange(10):
t=threading.Thread(target=task,args=[i,])
t.start()

d、实现基于metaclass的单例模式

1、对象为类创建,对象创建时为类__init__方法自动执行,对象()执行类 __call__ 方法。

2、type创建类别,type创建类别__init__方法自动执行,类() 执行type __call___法(类__法)new__方法,类____init_方法)。

#第0步:执行type___init__方法[类是type的对象]
classFoo:
def__init__(self):
pass

def__call__(self,*args,**kwargs):
pass

#第一步:执行type__call__方法
#1.1调用Fooo类(type的对象)__new__方法,用于创建对象。
#1.2调用Fooo类(type的对象)__init__方法用于对象的初始化。
obj=Foo()
#第二步:Foodef______call__方法
obj()
"""

importthreading

classSingletonType(type):
_instace_lock=threading.Lock()
def__call__(cls,*args,**kwargs):
ifnothasattr(cls,"_instance"):
withSingletonType._instace_lock:
ifnothasattr(cls,"_instance"):
cls._instance=super(SingletonType,cls).__call__(*args,**kwargs)
returncls._instance
classFoo(metaclass=SingletonType):
def__init__(self,name):
self.name=name

obj1=Foo('name')
obj2=Foo('name')
print(obj1,obj2)

相关文章

python3兼容python2吗

python3兼容python2吗

2025-05-09
python3 whl怎么安装

python3 whl怎么安装

2025-05-09
python 字典怎么提取value

python 字典怎么提取value

2025-05-09
python 怎样计算字符串的长度

python 怎样计算字符串的长度

2025-05-09
python 怎么样反向输出字符串

python 怎么样反向输出字符串

2025-05-09
python 怎么判断字符串开头

python 怎么判断字符串开头

2025-05-09