Python中单例模式总结
发布时间:2020-12-17 07:26:28 所属栏目:Python 来源:网络整理
导读:一、单例模式 a、单例模式分为四种:文件,类,基于__new__方法实现单例模式,基于metaclass方式实现 b、类实现如下: class Sigletion(objects): import time def __init__(self): time.sleep(1) @classmethod def instance(cls,*args,**kwargs) if not has
一、单例模式 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._instance import threading daf task(arg): obj=Sigletion.instance() print(obj) for i in range(10): t=threading.Thread(target=task,args=[i,]) t.start() c、基于__new__方法实现单例模式 import time import threading class Singleton(object): _instance_lock=threading.Lock() def __init__(self): pass def __new__(cls,**kwargs): if not hasattr(Singleton,"_instance"): with Singleton._instance_lock: if not hasattr(Singleton,"_instance"): Singleton._instance=object.__new__(cls,**kwargs) return Singleton._instance obj1=Singleton() obj2=Singleton() print(obj1,obj2) def task(arg): obj = Singleton() print(obj) for i in range(10): t = threading.Thread(target=task,]) t.start() d、基于metaclass方式实现单例模式 """ # 第0步: 执行type的 __init__ 方法【类是type的对象】 class Foo: def __init__(self): pass def __call__(self,**kwargs): pass # 第1步: 执行type的 __call__ 方法 # 1.1 调用 Foo类(是type的对象)的 __new__方法,用于创建对象。 # 1.2 调用 Foo类(是type的对象)的 __init__方法,用于对对象初始化。 obj = Foo() # 第2步:执行Foodef __call__ 方法 obj() """ import threading class SingletonType(type): _instace_lock=threading.Lock() def __call__(cls,**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._instance class Foo(metaclass=SingletonType): def __init__(self,name): self.name=name obj1 = Foo('name') obj2 = Foo('name') print(obj1,obj2) 您可能感兴趣的文章:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |