python 模块 多线程 单例_python的单例模式
一.單例模式
單例模式(Singleton Pattern)是一種常用的軟件設(shè)計(jì)模式,該模式的主要目的是確保某一個(gè)類(lèi)只有一個(gè)實(shí)例存在。當(dāng)你希望在整個(gè)系統(tǒng)中,某個(gè)類(lèi)只能出現(xiàn)一個(gè)實(shí)例時(shí),單例對(duì)象就能派上用場(chǎng)。
比如,某個(gè)服務(wù)器程序的配置信息存放在一個(gè)文件中,客戶(hù)端通過(guò)一個(gè) AppConfig 的類(lèi)來(lái)讀取配置文件的信息。如果在程序運(yùn)行期間,有很多地方都需要使用配置文件的內(nèi)容,也就是說(shuō),很多地方都需要?jiǎng)?chuàng)建 AppConfig 對(duì)象的實(shí)例,這就導(dǎo)致系統(tǒng)中存在多個(gè) AppConfig 的實(shí)例對(duì)象,而這樣會(huì)嚴(yán)重浪費(fèi)內(nèi)存資源,尤其是在配置文件內(nèi)容很多的情況下。事實(shí)上,類(lèi)似 AppConfig 這樣的類(lèi),我們希望在程序運(yùn)行期間只存在一個(gè)實(shí)例對(duì)象。
在 Python 中,我們可以用多種方法來(lái)實(shí)現(xiàn)單例模式。
二 .實(shí)現(xiàn)單例模式的幾種方式
2.1 使用模塊
其實(shí),Python 的模塊就是天然的單例模式,因?yàn)槟K在第一次導(dǎo)入時(shí),會(huì)生成?.pyc?文件,當(dāng)?shù)诙螌?dǎo)入時(shí),就會(huì)直接加載?.pyc?文件,而不會(huì)再次執(zhí)行模塊代碼。因此,我們只需把相關(guān)的函數(shù)和數(shù)據(jù)定義在一個(gè)模塊中,就可以獲得一個(gè)單例對(duì)象了。如果我們真的想要一個(gè)單例類(lèi),可以考慮這樣做:
mysingleton.py
class Singleton(object):
def foo(self):
pass
singleton = Singleton()
將上面的代碼保存在文件?mysingleton.py?中,要使用時(shí),直接在其他文件中導(dǎo)入此文件中的對(duì)象,這個(gè)對(duì)象即是單例模式的對(duì)象
from a import singleton
2.2 使用裝飾器
defSingleton(cls):
_instance={}def _singleton(*args, **kargs):if cls not in_instance:
_instance[cls]= cls(*args, **kargs)return_instance[cls]return_singleton
@SingletonclassA(object):
a= 1
def __init__(self, x=0):
self.x=x
a1= A(2)
a2= A(3)
2.3 使用類(lèi)
# 推薦
class Singleton(object):
__instance = None
def __new__(cls, age, name):
# 如果類(lèi)屬性__instance的值為None,
# 那么就創(chuàng)建一個(gè)對(duì)象,并且賦值為這個(gè)對(duì)象的引用,保證下次調(diào)用這個(gè)方法時(shí)
# 能夠知道之前已經(jīng)創(chuàng)建過(guò)對(duì)象了,這樣就保證了只有1個(gè)對(duì)象
if not cls.__instance:
cls.__instance = object.__new__(cls)
a = Singleton(18,'maomao')
b = Singleton(18,'alex')
print(id(a), id(b))
# 140732902316160 140732902316160
或者:
class Singleton(object):
def __init__(self):
pass
@classmethod
def instance(cls, *args, **kwargs):
if not hasattr(Singleton, "_instance"):
Singleton._instance = Singleton(*args, **kwargs)
return Singleton._instance
a = Singleton.instance()
b = Singleton.instance()
print(id(a), id(b))
注意:
這種方式實(shí)現(xiàn)的單例模式,使用時(shí)會(huì)有限制,以后實(shí)例化必須通過(guò)?obj = Singleton.instance()
如果用?obj=Singleton()?,這種方式得到的不是單例
注意:一般情況,大家以為這樣就完成了單例模式,但是這樣當(dāng)使用多線程時(shí)會(huì)存在問(wèn)題
importtimeimportthreadingclassSingleton(object):def __init__(self):
time.sleep(0.2)
@classmethoddef instance(cls, *args, **kwargs):if not hasattr(Singleton, "_instance"):
Singleton._instance= Singleton(*args, **kwargs)returnSingleton._instancedeftask(arg):
obj=Singleton.instance()print(obj)for i in range(10):
t= threading.Thread(target=task,args=[i,])
t.start()
打印結(jié)果:
問(wèn)題出現(xiàn)了!按照以上方式創(chuàng)建的單例,無(wú)法支持多線程
importtimeimportthreadingclassSingleton(object):
_instance_lock=threading.Lock()def __init__(self):
time.sleep(0.2)
@classmethoddef instance(cls, *args, **kwargs):
with Singleton._instance_lock:if not hasattr(Singleton, "_instance"):
Singleton._instance= Singleton(*args, **kwargs)returnSingleton._instancedeftask(arg):
obj=Singleton.instance()print(obj)for i in range(10):
t= threading.Thread(target=task,args=[i,])
t.start()
打印結(jié)果:
這樣就差不多了,但是還是有一點(diǎn)小問(wèn)題,就是當(dāng)程序執(zhí)行時(shí),執(zhí)行了time.sleep(20)后,下面實(shí)例化對(duì)象時(shí),此時(shí)已經(jīng)是單例模式了,但我們還是加了鎖,這樣不太好,
再進(jìn)行一些優(yōu)化,把intance方法,改成下面的這樣就行:
importtimeimportthreadingclassSingleton(object):
_instance_lock=threading.Lock()def __init__(self):
time.sleep(1)
@classmethoddef instance(cls, *args, **kwargs):if not hasattr(Singleton, "_instance"):
with Singleton._instance_lock:if not hasattr(Singleton, "_instance"):
Singleton._instance= Singleton(*args, **kwargs)returnSingleton._instancedeftask(arg):
obj=Singleton.instance()print(obj)for i in range(10):
t= threading.Thread(target=task,args=[i,])
t.start()
2.4 基于__new__方法實(shí)現(xiàn)(推薦)
通過(guò)上面例子,我們可以知道,當(dāng)我們實(shí)現(xiàn)單例時(shí),為了保證線程安全需要在內(nèi)部加入鎖
我們知道,當(dāng)我們實(shí)例化一個(gè)對(duì)象時(shí),是先執(zhí)行了類(lèi)的__new__方法(我們沒(méi)寫(xiě)時(shí),默認(rèn)調(diào)用object.__new__),實(shí)例化對(duì)象;然后再執(zhí)行類(lèi)的__init__方法,對(duì)這個(gè)對(duì)象進(jìn)行初始化,所有我們可以基于這個(gè),實(shí)現(xiàn)單例模式
importthreadingimporttimeclassSingleton(object):
_instance_lock=threading.Lock()def __init__(self):
time.sleep(1)def __new__(cls, *args, **kwargs):if not hasattr(Singleton, "_instance"):
with Singleton._instance_lock:if not hasattr(Singleton, "_instance"):
Singleton._instance= object.__new__(cls)returnSingleton._instancedeftask(arg):
obj=Singleton()print(obj)for i in range(10):
t= threading.Thread(target=task,args=[i,])
t.start()
2.5 基于metaclass實(shí)現(xiàn)單例模式
相關(guān)知識(shí):
執(zhí)行順序:
0. Mytype的__init__
obj = Foo()
1. MyType的__call__
2. Foo的__new__
3. Foo的__init__
實(shí)現(xiàn)單例模式:
importthreadingclassSingletonType(type):
_instance_lock=threading.Lock()def __call__(cls, *args, **kwargs):if not hasattr(cls, "_instance"):
with SingletonType._instance_lock:if not hasattr(cls, "_instance"):
cls._instance= super(SingletonType,cls).__call__(*args, **kwargs)returncls._instanceclass Foo(metaclass=SingletonType):def __init__(self,name):
self.name=name
obj1= Foo('name')
obj2= Foo('name')print(obj1,obj2)
總結(jié)
以上是生活随笔為你收集整理的python 模块 多线程 单例_python的单例模式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 对学校的希望和寄语_南中医举行2020年
- 下一篇: python dict update保持