Python实现单例模式的四种方式详解
作者:玩转测试开发 时间:2023-07-12 03:07:43
简介:单例模式可以保证一个类仅有一个实例,并提供一个访问它的全局访问点。适用性于当类只能有一个实例而且客户可以从一个众所周知的访问点访问它,例如访问数据库、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
标签:Python,单例模式
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
linux下mysql乱码问题的解决方案
2024-01-26 11:28:06
使用Django的模版来配合字符串翻译工作
2023-11-17 06:03:47
初探 SOA
2022-03-18 08:00:57
详解Go操作supervisor xml rpc接口及注意事项
2024-05-22 10:30:41
![](https://img.aspxhome.com/file/2023/2/123602_0s.jpg)
python 按照固定长度分割字符串的方法小结
2021-05-28 06:05:05
Python实现序列化及csv文件读取
2023-08-09 06:55:46
![](https://img.aspxhome.com/file/2023/2/64612_0s.png)
Oracle查看逻辑读、物理读资源占用排行的SQL语句
2023-06-25 23:53:53
Python+Pyecharts实现散点图的绘制
2023-09-02 05:01:29
![](https://img.aspxhome.com/file/2023/1/92211_0s.png)
Mysql将一个表中的某一列数据复制到另一个表中某一列里的方法
2024-01-14 17:36:29
![](https://img.aspxhome.com/file/2023/0/68050_0s.png)
Python descriptor(描述符)的实现
2021-12-22 09:07:56
![](https://img.aspxhome.com/file/2023/0/90400_0s.png)
教你使用webpack打包编译TypeScript代码
2024-06-10 22:53:32
Python实现选择排序
2021-06-17 03:23:40
OpenCV图像轮廓的绘制方法
2022-10-17 22:05:54
![](https://img.aspxhome.com/file/2023/8/95158_0s.jpg)
Python 通过调用接口获取公交信息的实例
2023-06-17 21:16:46
Ubuntu下mysql安装和操作图文教程
2024-01-25 15:53:30
![](https://img.aspxhome.com/file/2023/0/129880_0s.jpg)
Python解析nginx日志文件
2023-09-07 18:22:09
Python机器学习性能度量利用鸢尾花数据绘制P-R曲线
2023-01-27 20:55:48
![](https://img.aspxhome.com/file/2023/5/82905_0s.png)
使用python-cv2实现视频的分解与合成的示例代码
2021-06-21 11:51:46
php设计模式 Singleton(单例模式)
2023-11-20 14:37:50
go流程控制代码详解
2023-10-15 18:14:19