Python實現(xiàn)單例模式的四種方式詳解
簡介:單例模式可以保證一個類僅有一個實例,并提供一個訪問它的全局訪問點。適用性于當(dāng)類只能有一個實例而且客戶可以從一個眾所周知的訪問點訪問它,例如訪問數(shù)據(jù)庫、MQ等。
實現(xiàn)方式:
1、通過導(dǎo)入模塊實現(xiàn)
2、通過裝飾器實現(xiàn)
3、通過使用類實現(xiàn)
4、通過__new__ 方法實現(xiàn)
單例模塊方式被導(dǎo)入的源碼:singleton.py
# -*- coding: utf-8 -*- # time: 2022/5/17 10:31 # file: singleton.py # author: tom # 公眾號: 玩轉(zhuǎn)測試開發(fā) class Singleton(object): def __init__(self, name): self.name = name def run(self): print(self.name) s = Singleton("Tom")
主函數(shù)源碼:
# -*- coding: utf-8 -*- # time: 2022/5/17 10:51 # file: test_singleton.py # author: tom # 公眾號: 玩轉(zhuǎn)測試開發(fā) from singleton import s as s1 from singleton import s as s2 # Method One:通過導(dǎo)入模塊實現(xiàn) def show_method_one(): """ :return: """ print(s1) print(s2) print(id(s1)) print(id(s2)) show_method_one() # Method Two:通過裝飾器實現(xiàn) def singleton(cls): # 創(chuàng)建一個字典用來保存類的實例對象 _instance = {} def _singleton(*args, **kwargs): # 先判斷這個類有沒有對象 if cls not in _instance: _instance[cls] = cls(*args, **kwargs) # 創(chuàng)建一個對象,并保存到字典當(dāng)中 # 將實例對象返回 return _instance[cls] return _singleton @singleton class Demo2(object): a = 1 def __init__(self, x=0): self.x = x a1 = Demo2(1) a2 = Demo2(2) print(id(a1)) print(id(a2)) # Method Three:通過使用類實現(xiàn) class Demo3(object): # 靜態(tài)變量 _instance = None _flag = False def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance def __init__(self): if not Demo3._flag: Demo3._flag = True b1 = Demo3() b2 = Demo3() print(id(b1)) print(id(b2)) # Method Four:通過__new__ 方法實現(xiàn) class Demo4: def __new__(cls, *args, **kwargs): if not hasattr(cls, '_instance'): cls._instance = super(Demo4, cls).__new__(cls) return cls._instance c1 = Demo4() c2 = Demo4() print(id(c1)) print(id(c2))
運行結(jié)果:
到此這篇關(guān)于Python實現(xiàn)單例模式的四種方式詳解的文章就介紹到這了,更多相關(guān)Python單例模式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Pytorch中.detach()與.data的用法小結(jié)
這篇文章主要介紹了Pytorch中.detach()與.data的用法,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-07-07Python3使用騰訊云文字識別(騰訊OCR)提取圖片中的文字內(nèi)容實例詳解
這篇文章主要介紹了Python3使用騰訊云文字識別(騰訊OCR)提取圖片中的文字內(nèi)容方法詳解,需要的朋友可以參考下2020-02-02Django+Ajax+jQuery實現(xiàn)網(wǎng)頁動態(tài)更新的實例
今天小編就為大家分享一篇Django+Ajax+jQuery實現(xiàn)網(wǎng)頁動態(tài)更新的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05Python生產(chǎn)者與消費者模型中的優(yōu)勢介紹
這篇文章主要介紹了python多進程中的生產(chǎn)者和消費者模型優(yōu)勢,生產(chǎn)者是指生產(chǎn)數(shù)據(jù)的任務(wù),消費者是指消費數(shù)據(jù)的任務(wù)。當(dāng)生產(chǎn)者的生產(chǎn)能力遠大于消費者的消費能力,生產(chǎn)者就需要等消費者消費完才能繼續(xù)生產(chǎn)新的數(shù)據(jù)2023-03-03