Python實(shí)現(xiàn)單例模式的四種方式詳解
簡介:單例模式可以保證一個類僅有一個實(shí)例,并提供一個訪問它的全局訪問點(diǎn)。適用性于當(dāng)類只能有一個實(shí)例而且客戶可以從一個眾所周知的訪問點(diǎn)訪問它,例如訪問數(shù)據(jù)庫、MQ等。
實(shí)現(xiàn)方式:
1、通過導(dǎo)入模塊實(shí)現(xiàn)
2、通過裝飾器實(shí)現(xiàn)
3、通過使用類實(shí)現(xiàn)
4、通過__new__ 方法實(shí)現(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)入模塊實(shí)現(xiàn)
def show_method_one():
"""
:return:
"""
print(s1)
print(s2)
print(id(s1))
print(id(s2))
show_method_one()
# Method Two:通過裝飾器實(shí)現(xiàn)
def singleton(cls):
# 創(chuàng)建一個字典用來保存類的實(shí)例對象
_instance = {}
def _singleton(*args, **kwargs):
# 先判斷這個類有沒有對象
if cls not in _instance:
_instance[cls] = cls(*args, **kwargs) # 創(chuàng)建一個對象,并保存到字典當(dāng)中
# 將實(shí)例對象返回
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:通過使用類實(shí)現(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__ 方法實(shí)現(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))
運(yùn)行結(jié)果:

到此這篇關(guān)于Python實(shí)現(xiàn)單例模式的四種方式詳解的文章就介紹到這了,更多相關(guān)Python單例模式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python修改Excel數(shù)據(jù)的實(shí)例代碼
Python修改Excel數(shù)據(jù)的方法。2013-11-11
Django動態(tài)展示Pyecharts圖表數(shù)據(jù)的幾種方法
本文主要介紹了Django動態(tài)展示Pyecharts圖表數(shù)據(jù)的幾種方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-08-08
基于Python實(shí)現(xiàn)web網(wǎng)頁內(nèi)容爬取的方法
在日常學(xué)習(xí)和工作中,我們經(jīng)常會遇到需要爬取網(wǎng)頁內(nèi)容的需求,今天就如何基于Python實(shí)現(xiàn)web網(wǎng)頁內(nèi)容爬取進(jìn)行講解,感興趣的朋友一起看看吧2024-12-12
python3 requests庫實(shí)現(xiàn)多圖片爬取教程
今天小編就為大家分享一篇python3 requests庫實(shí)現(xiàn)多圖片爬取教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
python 安裝庫幾種方法之cmd,anaconda,pycharm詳解
在python項目開發(fā)的過程中,需要安裝大大小小的庫,本文會提供幾種安裝庫的方法,通過實(shí)例截圖給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下2020-04-04

