這篇文章主要為大家展示了“python如何實(shí)現(xiàn)單例模式”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“python如何實(shí)現(xiàn)單例模式”這篇文章吧。
方法一:使用裝飾器
裝飾器維護(hù)一個(gè)字典對(duì)象instances,緩存了所有單例類(lèi),只要單例不存在則創(chuàng)建,已經(jīng)存在直接返回該實(shí)例對(duì)象。
def singleton(cls): instances = {} def wrapper(*args, **kwargs): if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances[cls] return wrapper @singleton class Foo(object): pass foo1 = Foo() foo2 = Foo() print foo1 is foo2
方法二:使用基類(lèi)
__new__是真正創(chuàng)建實(shí)例對(duì)象的方法,所以重寫(xiě)基類(lèi)的__new__方法,以此來(lái)保證創(chuàng)建對(duì)象的時(shí)候只生成一個(gè)實(shí)例
class Singleton(object): def __new__(cls, *args, **kwargs): if not hasattr(cls, '_instance'): cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs) return cls._instance class Foo(Singleton): pass foo1 = Foo() foo2 = Foo() print foo1 is foo2 # True
方法三:使用元類(lèi)
元類(lèi)(參考:深刻理解Python中的元類(lèi))是用于創(chuàng)建類(lèi)對(duì)象的類(lèi),類(lèi)對(duì)象創(chuàng)建實(shí)例對(duì)象時(shí)一定會(huì)調(diào)用__call__方法,因此在調(diào)用__call__時(shí)候保證始終只創(chuàng)建一個(gè)實(shí)例即可,type是python中的一個(gè)元類(lèi)。
class Singleton(type): def __call__(cls, *args, **kwargs): if not hasattr(cls, '_instance'): cls._instance = super(Singleton, cls).__call__(*args, **kwargs) return cls._instance class Foo(object): __metaclass__ = Singleton foo1 = Foo() foo2 = Foo() print foo1 is foo2 # True
以上是“python如何實(shí)現(xiàn)單例模式”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
分享題目:python如何實(shí)現(xiàn)單例模式-創(chuàng)新互聯(lián)
新聞來(lái)源:http://www.rwnh.cn/article34/epipe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站導(dǎo)航、定制開(kāi)發(fā)、App設(shè)計(jì)、品牌網(wǎng)站設(shè)計(jì)、域名注冊(cè)、品牌網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容