網站首頁 編程語言 正文
簡介:單例模式可以保證一個類僅有一個實例,并提供一個訪問它的全局訪問點。適用性于當類只能有一個實例而且客戶可以從一個眾所周知的訪問點訪問它,例如訪問數據庫、MQ等。
實現方式:
1、通過導入模塊實現
2、通過裝飾器實現
3、通過使用類實現
4、通過__new__ 方法實現
單例模塊方式被導入的源碼:singleton.py
# -*- coding: utf-8 -*-
# time: 2022/5/17 10:31
# file: singleton.py
# author: tom
# 公眾號: 玩轉測試開發
class Singleton(object):
def __init__(self, name):
self.name = name
def run(self):
print(self.name)
s = Singleton("Tom")
主函數源碼:
# -*- coding: utf-8 -*-
# time: 2022/5/17 10:51
# file: test_singleton.py
# author: tom
# 公眾號: 玩轉測試開發
from singleton import s as s1
from singleton import s as s2
# Method One:通過導入模塊實現
def show_method_one():
"""
:return:
"""
print(s1)
print(s2)
print(id(s1))
print(id(s2))
show_method_one()
# Method Two:通過裝飾器實現
def singleton(cls):
# 創建一個字典用來保存類的實例對象
_instance = {}
def _singleton(*args, **kwargs):
# 先判斷這個類有沒有對象
if cls not in _instance:
_instance[cls] = cls(*args, **kwargs) # 創建一個對象,并保存到字典當中
# 將實例對象返回
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:通過使用類實現
class Demo3(object):
# 靜態變量
_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__ 方法實現
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))
運行結果:
原文鏈接:https://blog.csdn.net/hzblucky1314/article/details/124833122
相關推薦
- 2022-11-11 Python?GUI程序類寫法與Label介紹_python
- 2024-03-05 git的使用
- 2022-11-19 VSstudio中scanf返回值被忽略的原因及解決方法(推薦)_C 語言
- 2022-07-03 Golang之函數選項模式
- 2023-03-22 Linux?rm命令詳解?Linux刪除文件目錄的操作方法_linux shell
- 2022-05-26 Flutter?Drawer抽屜菜單示例詳解_Android
- 2022-01-29 yii restfull api 訪問404
- 2023-07-28 獲取當前日期以及前6天的日期集合
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支