python中的四种单例模式
2020-02-17 04:09
337 查看
1 # 单例模式:无法支持多线程情况 2 """ 3 class Singleton(object): 4 def __init__(self): 5 import time 6 time.sleep(1) 7 @classmethod 8 def instance(cls, *args, **kwargs): 9 if not hasattr(Singleton, "_instance"): 10 Singleton._instance = Singleton(*args, **kwargs) 11 return Singleton._instance 12 import threading 13 14 def task(arg): 15 obj = Singleton.instance() 16 print(obj) 17 18 for i in range(10): 19 t = threading.Thread(target=task,args=[i,]) 20 t.start()第一种
1 import time 2 import threading 3 class Singleton(object): 4 _instance_lock = threading.Lock() 5 def __init__(self): 6 time.sleep(4) 7 @classmethod 8 def instance(cls, *args, **kwargs): 9 if not hasattr(Singleton, "_instance"): 10 with Singleton._instance_lock: 11 if not hasattr(Singleton, "_instance"): 12 Singleton._instance = Singleton(*args, **kwargs) 13 return Singleton._instance 14 def task(arg): 15 obj = Singleton.instance() 16 print(obj) 17 for i in range(10): 18 t = threading.Thread(target=task,args=[i,]) 19 t.start() 20 obj = Singleton.instance() 21 print(obj)第二种
1 import time 2 import threading 3 class Singleton(object): 4 _instance_lock = threading.Lock() 5 def __init__(self): 6 pass 7 def __new__(cls, *args, **kwargs): 8 if not hasattr(Singleton, "_instance"): 9 with Singleton._instance_lock: 10 if not hasattr(Singleton, "_instance"): 11 Singleton._instance = object.__new__(cls, *args, **kwargs) 12 return Singleton._instance 13 obj1 = Singleton() 14 obj2 = Singleton() 15 print(obj1,obj2)第三种
1 import threading 2 class SingletonType(type): 3 _instance_lock = threading.Lock() 4 def __call__(cls, *args, **kwargs): 5 if not hasattr(cls, "_instance"): 6 with SingletonType._instance_lock: 7 if not hasattr(cls, "_instance"): 8 cls._instance = super(SingletonType,cls).__call__(*args, **kwargs) 9 return cls._instance 10 class Foo(metaclass=SingletonType): 11 def __init__(self,name): 12 self.name = name 13 obj1 = Foo('name') 14 obj2 = Foo('name') 15 print(obj1,obj2)第四种
转载于:https://www.cnblogs.com/sxh-myblogs/p/8244813.html
-
20000
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- 贝叶斯定理_python实现_1_贝叶斯基础
- numpy实现分段函数
- python平铺多维列表
- Python的import模块&如何创建自己的模块
- 查看Python已安装的模块
- Python数据类型之整数和字符串常用功能
- Python实现内容检索子系统(BM25算法)
- python3.7 ImportError: No module named _ssl 解决方法
- 基于Python Django的慕课网校教育平台的开发(一)
- Learning Python for Natural Network (01)
- Ubuntu 16.0.4 中默认的Python2环境切换为Python3
- 密度聚类DBSCAN算法代码超详细注释(python版)
- Center OS下安装python3
- Python中print单引号、双引号、三引号
- python基础--print()函数、变量定义、转义字符
- Python | 导包 ModuleNotFoundError: No module named 'xxx'
- python学习day01
- AttributeError错误,用的是python3,jango2.1为什么回报错是因为ForeignKeys不存在?
- win10 anaconda python3.6多虚拟环境使用VScode配置
- 学习笔记(04):跟着王进老师学开发:Python初级入门课程-身份运算符