Python?設(shè)計模式創(chuàng)建型單例模式
一、單例模式
單例模式,實(shí)現(xiàn)一個類,并且保證這個類的多次實(shí)例化操作,都會只生成同一個實(shí)例對象。
二、應(yīng)用場景
整個系統(tǒng)中只需要存在一個實(shí)例對象,其他對象都可以通過訪問該對象來獲取信息,比如:
- 系統(tǒng)的配置信息對象
- 日志對象
- 數(shù)據(jù)庫操作對象
- 線程池對象
三、編碼示例
1.單線程中的單例模式
方式一、重載類構(gòu)造器
定義:
class Singleton(object): ? ? _instance = None ? ? def __new__(cls, *args, **kwargs): ? ? ? ? if cls._instance is None: ? ? ? ? ? ? cls._instance = object.__new__(cls, *args, **kwargs) ? ? ? ? return cls._instance
使用:
if __name__ == '__main__': ? ? instance1 = Singleton() ? ? instance2 = Singleton() ? ? instance3 = Singleton() ? ? # 打印出 3 個實(shí)例對象的內(nèi)存地址,判斷是否相同。 ? ? print(id(instance1)) ? ? print(id(instance2)) ? ? print(id(instance3))
方式二、實(shí)現(xiàn)單例裝飾器
定義:
def singleton(cls): ? ? _instance = {} ? ? def _singleton(*args, **kargs): ? ? ? ? if cls not in _instance: ? ? ? ? ? ? _instance[cls] = cls(*args, **kargs) ? ? ? ? return _instance[cls] ? ? return _singleton
使用:
@singleton class Singleton(object): ? ? """單例實(shí)例""" ? ? def __init__(self, arg1): ? ? ? ? self.arg1 = arg1 if __name__ == '__main__': ? ? instance1 = Singleton("xag") ? ? instance2 = Singleton("xingag") ? ? print(id(instance1)) ? ? print(id(instance2))
2.多線程中的單例模式
方式三、重載具有線程鎖的類構(gòu)造器
多線程中的單例模式,需要在__new__
構(gòu)造器中使用threading.Lock()
同步鎖。
定義:
class Singleton(object): ? ? _instance = None ? ? _instance_lock = threading.Lock() ? ? def __new__(cls, *args, **kwargs): ? ? ? ? if cls._instance is None: ? ? ? ? ? ? with cls._instance_lock: ? ? ? ? ? ? ? ? cls._instance = object.__new__(cls, *args, **kwargs) ? ? ? ? return cls._instance
使用:
def task(arg): ? ? instance = Singleton() ? ? print(id(instance), '\n') if __name__ == '__main__': ? ? for i in range(3): ? ? ? ? t = threading.Thread(target=task, args=[i, ]) ? ? ? ? t.start()
到此這篇關(guān)于Python 設(shè)計模式創(chuàng)建型單例模式的文章就介紹到這了,更多相關(guān)Python 單例模式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python獲取二維數(shù)組的行列數(shù)的2種方法
這篇文章主要介紹了Python獲取二維數(shù)組的行列數(shù)的2種方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-02-02Python中用startswith()函數(shù)判斷字符串開頭的教程
這篇文章主要介紹了Python中用startswith()函數(shù)判斷字符串開頭的教程,startswith()函數(shù)的使用是Python學(xué)習(xí)中的基礎(chǔ)知識,本文列舉了一些不同情況下的使用結(jié)果,需要的朋友可以參考下2015-04-04對python while循環(huán)和雙重循環(huán)的實(shí)例詳解
今天小編就為大家分享一篇對python while循環(huán)和雙重循環(huán)的實(shí)例詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08利用Python實(shí)現(xiàn)生成顏色表(color chart)
在做色彩相關(guān)的算法分析時候,經(jīng)常需要使用規(guī)則的顏色表來進(jìn)行輔助,本文就來利用numpy和opencv生成顏色表并保存為圖片,需要的可以參考一下2023-05-05keras load model時出現(xiàn)Missing Layer錯誤的解決方式
這篇文章主要介紹了keras load model時出現(xiàn)Missing Layer錯誤的解決方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06python實(shí)現(xiàn)敲木魚加功德包含加音效和敲擊動作(附demo)
敲木魚加功德是一款很火的動畫,本文主要介紹了python實(shí)現(xiàn)敲木魚加功德包含加音效和敲擊動作,具有一定的參考價值,感興趣的可以了解一下2023-11-11