Python实现单例模式的四种方式详解
Admin 2022-08-22 群英技术资讯 473 次浏览
简介:单例模式可以保证一个类仅有一个实例,并提供一个访问它的全局访问点。适用性于当类只能有一个实例而且客户可以从一个众所周知的访问点访问它,例如访问数据库、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))
运行结果:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
这篇文章主要介绍了实现 Python 脚本生成命令行,文章通过定义一个 scrape 方法展开详细内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
这篇文章主要介绍了python实战之用emoji表情生成文字,文中有非常详细的代码示例,对正在学习python的小伙伴们有很好地帮助,需要的朋友可以参考下
对于Python语言来说,比较传统的数据可视化模块是Matplotlib,但它存在不够美观、静态性、不易分享等缺点,限制了Python在数据可视化方面的发展。为了解决这个问题,新型的动态可视化开源模块Plotly应运而生。本文将为大家详细介绍Plotly的用法,需要的可以参考一下
我们在Django项目中可能会使用到render()函数,但是很多新手可能不知道render()函数的使用,对此,下面小编就给大家分享一个render()函数的用法,感兴趣的朋友可以看看。
本文主要介绍了python beautifulsoup4模块详情,BeautifulSoup4是一款python解析库,主要用于解析HTML和XML,在爬虫知识体系中解析 HTML 会比较多一些,下文更多相关内容,需要的小伙伴可以参考一下
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008