Python的四種單例模式實(shí)現(xiàn)方式
★ 單例模式基本介紹
單例模式是一種設(shè)計(jì)模式,用于確保一個(gè)類只有一個(gè)實(shí)例,并提供全局訪問(wèn)點(diǎn)以獲取該實(shí)例。它是一種創(chuàng)建型模式,通常用于需要嚴(yán)格控制某個(gè)類的實(shí)例數(shù)量的情況。單例模式確保一個(gè)類在整個(gè)應(yīng)用程序生命周期中只有一個(gè)實(shí)例,因此可以節(jié)省系統(tǒng)資源,同時(shí)提供了一個(gè)集中的訪問(wèn)點(diǎn),以便在需要時(shí)獲取該實(shí)例。
★ 實(shí)現(xiàn)單例的幾種方式:
- 模塊導(dǎo)入
- 添加裝飾器(類裝飾器和函數(shù)裝飾器)
- 重寫(xiě)new方法
- 元類繼承
★ 方式一: 模塊導(dǎo)入
文件結(jié)構(gòu)
單例 ├───file1.py ├───file2.py ├───readme ├───單例實(shí)現(xiàn)1_模塊導(dǎo)入.py └───模塊導(dǎo)入實(shí)現(xiàn)單例測(cè)試.py
單例實(shí)現(xiàn)1_模塊導(dǎo)入.py
""" 模塊導(dǎo)入實(shí)現(xiàn)單例模式步驟: 1. 在模塊中定義類 2. 實(shí)例化類并返回 3. 在其他文件中導(dǎo)入實(shí)例對(duì)象使用, 每個(gè)文件導(dǎo)入的對(duì)象實(shí)際是同一個(gè) """ class Singleton: def __init__(self, name): self.name = name def do_something(self): pass singleton = Singleton('模塊單例') # 在其他py文件中 # from my_singleton import singleton
file1.py
from 單例實(shí)現(xiàn)1_模塊導(dǎo)入 import singleton print(singleton)
file2.py
from 單例實(shí)現(xiàn)1_模塊導(dǎo)入 import singleton print(singleton)
模塊導(dǎo)入實(shí)現(xiàn)單例測(cè)試.py
import file1 import file2 print(file1.singleton is file2.singleton)
執(zhí)行結(jié)果
<單例實(shí)現(xiàn)1_模塊導(dǎo)入.Singleton object at 0x0000021B2B81F400>
<單例實(shí)現(xiàn)1_模塊導(dǎo)入.Singleton object at 0x0000021B2B81F400>
True
★ 方式二: 裝飾器
單例實(shí)現(xiàn)2_裝飾器.py
# -------------------函數(shù)裝飾器--------------------------- def Singleton1(cls): instance = {} def _singleton_wrapper(*args, **kargs): if cls not in instance: instance[cls] = cls(*args, **kargs) return instance[cls] return _singleton_wrapper # -------------------類裝飾器--------------------------- class Singleton2: def __init__(self, cls): self.cls = cls self._instance = None def __call__(self, *args, **kwargs): if not self._instance: self._instance = self.cls(*args, **kwargs) return self._instance # SingletonTest = Singleton1(SingletonTest) =_singleton_wrapper # SingletonTest = Singleton2(SingletonTest) = Singleton2實(shí)例對(duì)象 @Singleton1 class SingletonTest(object): def __init__(self, name): print(">>> 初始化 <<<") self.name = name s1 = SingletonTest('s1') s2 = SingletonTest('s2') print(s1, s2) print(s1 is s2)
執(zhí)行結(jié)果
>>> 初始化 <<<
<__main__.SingletonTest object at 0x000001E6A2FF73D0> <__main__.SingletonTest object at 0x000001E6A2FF73D0>
True
★ 方式三: 重寫(xiě)new方法
單例實(shí)現(xiàn)3_重寫(xiě)new方法.py
class Singleton(object): def __new__(cls, *args, **kwargs): if not hasattr(Singleton, "_instance"): Singleton._init_flag = True Singleton._instance = super().__new__(cls) return Singleton._instance def __init__(self, name): if not hasattr(Singleton, "_init"): Singleton._init = True print(">>> 初始化 <<<") self.name = name s1 = Singleton('s1') s2 = Singleton('s2') print(s1, s2) print(s1 is s2)
執(zhí)行結(jié)果
>>> 初始化 <<<
<__main__.Singleton object at 0x0000016663140760> <__main__.Singleton object at 0x0000016663140760>
True
★ 方式四: 元類繼承
單例實(shí)現(xiàn)4_元類繼承.py
class Singleton(type): def __call__(cls, *args, **kwargs): if not hasattr(Singleton, "_instance"): # cls 是 Singleton 創(chuàng)建的類 Singleton._instance = cls.__new__(cls, *args, **kwargs) cls.__init__(Singleton._instance, *args, **kwargs) return Singleton._instance class SingletonTest(metaclass=Singleton): pass class A(SingletonTest): def __init__(self, name): print(">>> 初始化 <<<") self.name = name s1 = A('s1') s2 = A('s2') print(s1, s2) print(s1 is s2)
執(zhí)行結(jié)果
>>> 初始化 <<<
<__main__.A object at 0x000001687C79D5E0> <__main__.A object at 0x000001687C79D5E0>
True
到此這篇關(guān)于Python的四種單例模式實(shí)現(xiàn)方式的文章就介紹到這了,更多相關(guān)Python單例模式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python實(shí)現(xiàn)單例模式的四種方法
- Python 中單例模式的實(shí)現(xiàn)方法
- Python實(shí)現(xiàn)單例模式的五種寫(xiě)法總結(jié)
- Python?reflect單例模式反射各個(gè)函數(shù)
- Python實(shí)現(xiàn)單例模式的四種方式詳解
- python設(shè)計(jì)模式之單例模式你了解多少
- Python中的單例模式與反射機(jī)制詳解
- Python實(shí)現(xiàn)單例模式的5種方法
- python單例模式的應(yīng)用場(chǎng)景實(shí)例講解
- Python單例模式的5種實(shí)現(xiàn)方式
相關(guān)文章
python中Pyqt5使用Qlabel標(biāo)簽進(jìn)行視頻播放
這篇文章主要介紹了python中Pyqt5使用Qlabel實(shí)現(xiàn)標(biāo)簽進(jìn)行視頻播放,QLabel是界面中的標(biāo)簽類,繼承自QFrame類,提供文本和圖像的顯示,是一種展示控件,下文相關(guān)內(nèi)容介紹需要的小伙伴可以參考一下2022-04-04python使用paramiko實(shí)現(xiàn)ssh的功能詳解
這篇文章主要介紹了python使用paramiko實(shí)現(xiàn)ssh的功能詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03Python使用LSTM實(shí)現(xiàn)銷售額預(yù)測(cè)詳解
大家經(jīng)常會(huì)遇到一些需要預(yù)測(cè)的場(chǎng)景,比如預(yù)測(cè)品牌銷售額,預(yù)測(cè)產(chǎn)品銷量。本文給大家分享一波使用?LSTM?進(jìn)行端到端時(shí)間序列預(yù)測(cè)的完整代碼和詳細(xì)解釋,需要的可以參考一下2022-07-07對(duì)python pandas 畫(huà)移動(dòng)平均線的方法詳解
今天小編就為大家分享一篇對(duì)python pandas 畫(huà)移動(dòng)平均線的方法詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-11-11基于Python實(shí)現(xiàn)PDF批量轉(zhuǎn)化工具
這篇文章主要為大家詳細(xì)介紹了如何基于Python制作一個(gè)PDF批量轉(zhuǎn)化工具,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-12-12深入解析NumPy中的Broadcasting廣播機(jī)制
在吳恩達(dá)老師的深度學(xué)習(xí)專項(xiàng)課程中,老師有提到NumPy中的廣播機(jī)制,同時(shí)那一周的測(cè)驗(yàn)也有涉及到廣播機(jī)制的題目。那么,到底什么是NumPy中的廣播機(jī)制?本文就來(lái)介紹一下2021-05-05