單利模式及python實(shí)現(xiàn)方式詳解
單例模式
單例模式(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實(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í)行了類(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._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ì)都是通過(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ì)腳本之家網(wǎng)站的支持!
相關(guān)文章
Python 中pandas.read_excel詳細(xì)介紹
這篇文章主要介紹了Python 中pandas.read_excel詳細(xì)介紹的相關(guān)資料,需要的朋友可以參考下2017-06-06
Python 序列化和反序列化庫(kù) MarshMallow 的用法實(shí)例代碼
marshmallow(Object serialization and deserialization, lightweight and fluffy.)用于對(duì)對(duì)象進(jìn)行序列化和反序列化,并同步進(jìn)行數(shù)據(jù)驗(yàn)證。這篇文章主要介紹了Python 序列化和反序列化庫(kù) MarshMallow 的用法實(shí)例代碼,需要的朋友可以參考下2020-02-02
Python中的默認(rèn)參數(shù)實(shí)例分析
這篇文章主要介紹了Python中的默認(rèn)參數(shù)實(shí)例分析,分享了相關(guān)代碼示例,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01
python自動(dòng)循環(huán)定時(shí)開(kāi)關(guān)機(jī)(非重啟)測(cè)試
這篇文章主要為大家詳細(xì)介紹了python自動(dòng)循環(huán)定時(shí)開(kāi)關(guān)機(jī)(非重啟)測(cè)試,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-08-08
Python中使用雙下劃線防止類(lèi)屬性被覆蓋問(wèn)題
這篇文章主要介紹了Python中使用雙下劃線防止類(lèi)屬性被覆蓋,需要的朋友可以參考下2019-06-06
python3實(shí)現(xiàn)全角和半角字符轉(zhuǎn)換的方法示例
在自然語(yǔ)言處理過(guò)程中,全角、半角的的不一致會(huì)導(dǎo)致信息抽取不一致,因此需要統(tǒng)一,下面這篇文章主要給大家介紹了關(guān)于python3中全角和半角字符轉(zhuǎn)換的方法,需要的朋友可以參考借鑒,下面來(lái)一起看看吧。2017-09-09
Python爬蟲(chóng)實(shí)現(xiàn)“盜取”微信好友信息的方法分析
這篇文章主要介紹了Python爬蟲(chóng)實(shí)現(xiàn)“盜取”微信好友信息的方法,結(jié)合實(shí)例形式分析了Python針對(duì)微信數(shù)據(jù)信息爬取的相關(guān)操作技巧,需要的朋友可以參考下2019-09-09
python內(nèi)置模塊OS?實(shí)現(xiàn)SHELL端文件處理器
這篇文章主要介紹了python內(nèi)置模塊OS實(shí)現(xiàn)SHELL端文件處理器,文章通過(guò)圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-09-09
Jupyter Notebook如何導(dǎo)入python文件時(shí)的問(wèn)題
這篇文章主要介紹了Jupyter Notebook如何導(dǎo)入python文件時(shí)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07
Python基于生成器迭代實(shí)現(xiàn)的八皇后問(wèn)題示例
這篇文章主要介紹了Python基于生成器迭代實(shí)現(xiàn)的八皇后問(wèn)題,簡(jiǎn)單描述了八皇后問(wèn)題,并結(jié)合實(shí)例形式分析了Python基于生成器迭代解決八皇后問(wèn)題的相關(guān)操作技巧,需要的朋友可以參考下2018-05-05

