單利模式及python實(shí)現(xiàn)方式詳解
單例模式
單例模式(Singleton Pattern)是一種常用的軟件設(shè)計(jì)模式,該模式的主要目的是確保 某一個(gè)類只有一個(gè)實(shí)例存在 。當(dāng)希望在整個(gè)系統(tǒng)中,某個(gè)類只能出現(xiàn)一個(gè)實(shí)例時(shí),單例對(duì)象就能派上用場(chǎng)。
比如,某個(gè)服務(wù)器程序的配置信息存放在一個(gè)文件中,客戶端通過一個(gè) AppConfig 的類來讀取配置文件的信息。如果在程序運(yùn)行期間,有很多地方都需要使用配置文件的內(nèi)容,也就是說,很多地方都需要?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í)上,類似 AppConfig 這樣的類,我們希望在程序運(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 singleton singleton.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 @singleton class A(object): def __init__(self, x=0): self.x = x a1 = A(2) a2 = A(3)
最終實(shí)例化出一個(gè)對(duì)象并且保存在_instance中,_instance的值也一定是
基于__new__方法實(shí)現(xiàn)
當(dāng)我們實(shí)例化一個(gè)對(duì)象時(shí),是 先執(zhí)行了類的__new__方法 (我們沒寫時(shí),默認(rèn)調(diào)用object.__new__), 實(shí)例化對(duì)象 ;然后 再執(zhí)行類的__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._instance class A(Singleton): def __init__(self,x): self.x=x a=A('han') b=A('tao') print(a.x) print(b.x)
為了保證線程安全需要在內(nèi)部加入鎖
import threading class 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._instance class A(Singleton): def __init__(self,x): self.x=x a=A('han') b=A('tao') print(a.x) print(b.x)
兩大注意:
1. 除了模塊單例外,其他幾種模式的本質(zhì)都是通過設(shè)置中間變量,來判斷類是否已經(jīng)被實(shí)例。中間變量的訪問和更改存在線程安全的問題:在開啟多線程模式的時(shí)候需要加鎖處理。
2. __new__方法無法避免觸發(fā)__init__(),初始的成員變量會(huì)進(jìn)行覆蓋。 其他方法不會(huì)。
PS:下面看下Python單例模式的4種實(shí)現(xiàn)方法
#-*- encoding=utf-8 -*- print '----------------------方法1--------------------------' #方法1,實(shí)現(xiàn)__new__方法 #并在將一個(gè)類的實(shí)例綁定到類變量_instance上, #如果cls._instance為None說明該類還沒有實(shí)例化過,實(shí)例化該類,并返回 #如果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è)類的所有實(shí)例天然擁有相同的行為(方法), #只需要保證同一個(gè)類的所有實(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__屬性),見: print id(one.__dict__) #30104000 print id(two.__dict__) #30104000 print '----------------------方法3--------------------------' #方法3:本質(zhì)上是方法1的升級(jí)(或者說高級(jí))版 #使用__metaclass__(元類)的高級(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的方法, #單例類本身根本不知道自己是單例的,因?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ì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
Python+tkinter使用40行代碼實(shí)現(xiàn)計(jì)算器功能
這篇文章主要為大家詳細(xì)介紹了Python+tkinter使用40行代碼實(shí)現(xiàn)計(jì)算器功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01Python基于requests實(shí)現(xiàn)模擬上傳文件
這篇文章主要介紹了Python基于requests實(shí)現(xiàn)模擬上傳文件,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04Python實(shí)現(xiàn)多進(jìn)程的四種方式
今天小編就為大家分享一篇關(guān)于Python實(shí)現(xiàn)多進(jìn)程的四種方式,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-02-02python json.loads兼容單引號(hào)數(shù)據(jù)的方法
今天小編就為大家分享一篇python json.loads兼容單引號(hào)數(shù)據(jù)的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-12-12

人工智能學(xué)習(xí)Pytorch教程Tensor基本操作示例詳解