單例模式
單例模式(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è)文件中,客戶端通過(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實(shí)現(xiàn)單例模式
使用模塊實(shí)現(xiàn)
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ì)象了。
mysingleton.py
class Singleton: def foo(self): print('foo')singleton=Singleton()其他文件
from mysingleton import singletonsingleton.foo()
裝飾器實(shí)現(xiàn)
def singleton(cls): _instance = {} def wraper(*args, **kargs): if cls not in _instance: _instance[cls] = cls(*args, **kargs) return _instance[cls] return wraper@singletonclass A(object): def __init__(self, x=0): self.x = xa1 = A(2)a2 = A(3)最終實(shí)例化出一個(gè)對(duì)象并且保存在_instance中,_instance的值也一定是
基于__new__方法實(shí)現(xiàn)
當(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)單例模式
class Singleton(): def __new__(cls, *args, **kwargs): if not hasattr(cls,'_instance'): cls._instance=object.__new__(cls) return cls._instanceclass A(Singleton): def __init__(self,x): self.x=xa=A('han')b=A('tao')print(a.x)print(b.x)為了保證線程安全需要在內(nèi)部加入鎖
import threadingclass Singleton(): lock=threading.Lock def __new__(cls, *args, **kwargs): if not hasattr(cls,'_instance'): with cls.lock: if not hasattr(cls, '_instance'): cls._instance=object.__new__(cls) return cls._instanceclass A(Singleton): def __init__(self,x): self.x=xa=A('han')b=A('tao')print(a.x)print(b.x)兩大注意:
1. 除了模塊單例外,其他幾種模式的本質(zhì)都是通過(guò)設(shè)置中間變量,來(lái)判斷類(lèi)是否已經(jīng)被實(shí)例。中間變量的訪問(wèn)和更改存在線程安全的問(wèn)題:在開(kāi)啟多線程模式的時(shí)候需要加鎖處理。
2. __new__方法無(wú)法避免觸發(fā)__init__(),初始的成員變量會(huì)進(jìn)行覆蓋。 其他方法不會(huì)。
PS:下面看下Python單例模式的4種實(shí)現(xiàn)方法
#-*- encoding=utf-8 -*- print '----------------------方法1--------------------------' #方法1,實(shí)現(xiàn)__new__方法 #并在將一個(gè)類(lèi)的實(shí)例綁定到類(lèi)變量_instance上, #如果cls._instance為None說(shuō)明該類(lèi)還沒(méi)有實(shí)例化過(guò),實(shí)例化該類(lèi),并返回 #如果cls._instance不為None,直接返回cls._instance class Singleton(object): def __new__(cls, *args, **kw): if not hasattr(cls, '_instance'): orig = super(Singleton, cls) cls._instance = orig.__new__(cls, *args, **kw) return cls._instance class MyClass(Singleton): a = 1 one = MyClass() two = MyClass() two.a = 3 print one.a #3 #one和two完全相同,可以用id(), ==, is檢測(cè) print id(one) #29097904 print id(two) #29097904 print one == two #True print one is two #True print '----------------------方法2--------------------------' #方法2,共享屬性;所謂單例就是所有引用(實(shí)例、對(duì)象)擁有相同的狀態(tài)(屬性)和行為(方法) #同一個(gè)類(lèi)的所有實(shí)例天然擁有相同的行為(方法), #只需要保證同一個(gè)類(lèi)的所有實(shí)例具有相同的狀態(tài)(屬性)即可 #所有實(shí)例共享屬性的最簡(jiǎn)單最直接的方法就是__dict__屬性指向(引用)同一個(gè)字典(dict) #可參看:http://code.activestate.com/recipes/66531/ class Borg(object): _state = {} def __new__(cls, *args, **kw): ob = super(Borg, cls).__new__(cls, *args, **kw) ob.__dict__ = cls._state return ob class MyClass2(Borg): a = 1 one = MyClass2() two = MyClass2() #one和two是兩個(gè)不同的對(duì)象,id, ==, is對(duì)比結(jié)果可看出 two.a = 3 print one.a #3 print id(one) #28873680 print id(two) #28873712 print one == two #False print one is two #False #但是one和two具有相同的(同一個(gè)__dict__屬性),見(jiàn): print id(one.__dict__) #30104000 print id(two.__dict__) #30104000 print '----------------------方法3--------------------------' #方法3:本質(zhì)上是方法1的升級(jí)(或者說(shuō)高級(jí))版 #使用__metaclass__(元類(lèi))的高級(jí)python用法 class Singleton2(type): def __init__(cls, name, bases, dict): super(Singleton2, cls).__init__(name, bases, dict) cls._instance = None def __call__(cls, *args, **kw): if cls._instance is None: cls._instance = super(Singleton2, cls).__call__(*args, **kw) return cls._instance class MyClass3(object): __metaclass__ = Singleton2 one = MyClass3() two = MyClass3() two.a = 3 print one.a #3 print id(one) #31495472 print id(two) #31495472 print one == two #True print one is two #True print '----------------------方法4--------------------------' #方法4:也是方法1的升級(jí)(高級(jí))版本, #使用裝飾器(decorator), #這是一種更pythonic,更elegant的方法, #單例類(lèi)本身根本不知道自己是單例的,因?yàn)樗旧?自己的代碼)并不是單例的 def singleton(cls, *args, **kw): instances = {} def _singleton(): if cls not in instances: instances[cls] = cls(*args, **kw) return instances[cls] return _singleton @singleton class MyClass4(object): a = 1 def __init__(self, x=0): self.x = x one = MyClass4() two = MyClass4() two.a = 3 print one.a #3 print id(one) #29660784 print id(two) #29660784 print one == two #True print one is two #True one.x = 1 print one.x #1 print two.x #1 總結(jié)
以上所述是小編給大家介紹的python實(shí)現(xiàn)單利模式方式方式詳解,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)VEVB武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選