Python中单例模式总结
Python  /  管理员 发布于 7年前   193
一、单例模式
a、单例模式分为四种:文件,类,基于__new__方法实现单例模式,基于metaclass方式实现
b、类实现如下:
class Sigletion(objects): import time def __init__(self): time.sleep(1) @classmethod def instance(cls,*args,**kwargs) if not hasattr(Sigletion,'_instance'): Sigletion._instance=Sigletion(*args,**kwargs) return Sigletion._instanceimport threadingdaf task(arg): obj=Sigletion.instance() print(obj)for i in range(10): t=threading.Thread(target=task,args=[i,]) t.start()
c、基于__new__方法实现单例模式
import timeimport threadingclass Singleton(object): _instance_lock=threading.Lock() def __init__(self): pass def __new__(cls, *args, **kwargs): if not hasattr(Singleton,"_instance"): with Singleton._instance_lock: if not hasattr(Singleton,"_instance"): Singleton._instance=object.__new__(cls,*args,**kwargs) return Singleton._instanceobj1=Singleton()obj2=Singleton()print(obj1,obj2)def task(arg): obj = Singleton() print(obj)for i in range(10): t = threading.Thread(target=task,args=[i,]) t.start()
d、基于metaclass方式实现单例模式
"""
1.对象是类创建,创建对象时候类的__init__方法自动执行,对象()执行类的 __call__ 方法
2.类是type创建,创建类时候type的__init__方法自动执行,类() 执行type的 __call__方法(类的__new__方法,类的__init__方法)
# 第0步: 执行type的 __init__ 方法【类是type的对象】class Foo: def __init__(self): pass def __call__(self, *args, **kwargs): pass# 第1步: 执行type的 __call__ 方法# 1.1 调用 Foo类(是type的对象)的 __new__方法,用于创建对象。# 1.2 调用 Foo类(是type的对象)的 __init__方法,用于对对象初始化。obj = Foo()# 第2步:执行Foodef __call__ 方法obj()"""import threadingclass SingletonType(type): _instace_lock=threading.Lock() def __call__(cls, *args, **kwargs): if not hasattr(cls, "_instance"): with SingletonType._instace_lock: if not hasattr(cls, "_instance"): cls._instance = super(SingletonType,cls).__call__(*args, **kwargs) return cls._instanceclass Foo(metaclass=SingletonType): def __init__(self,name): self.name=nameobj1 = Foo('name')obj2 = Foo('name')print(obj1,obj2)
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号