温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

什么是python的单例模式

发布时间:2020-09-10 17:35:05 来源:亿速云 阅读:210 作者:Leah 栏目:编程语言

今天就跟大家聊聊有关什么是python的单例模式,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在。当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场。

单例模式

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, *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._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,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 threading   class 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._instance class Foo(metaclass=SingletonType):   def __init__(self,name):     self.name=name    obj1 = Foo('name') obj2 = Foo('name') print(obj1,obj2)

看完上述内容,你们对什么是python的单例模式有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI