zoukankan      html  css  js  c++  java
  • 单例模式

    一、单例模式

         单例模式分为四种:1.文件,2.类,3.基于__new__方法实现单例模式,4.基于metaclass方式实现

    2.类实现如下:

    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()
    类实现的-单例模式无法支持多线程的情况
    import time
    import threading
    class Sigletion(object):
        _instance_lock=threading.Lock()
        def __init__(self):
            time.sleep(1)
        @classmethod
        def instance(cls,*args,**kwargs):
            if not hasattr(Sigletion,'_instance'):
                with Sigletion._instance_lock:
                    if not hasattr(Sigletion,"_instace"):
                        Sigletion._instance=Sigletion(*args,**kwargs)
            return Sigletion._instance
    
    def task(arg):
        obj=Sigletion.instance()
        print(obj)
    
    for i in range(10):
        t=threading.Thread(target=task,args=[i,])
        t.start()
    time.sleep(20)
    obj=Sigletion.instance()
    print(obj)
    类实现的-单例模式无法支持多线程的情况

    3.基于__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()
    基于__new__方法实现的单例模式

    4.基于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)
    基于metaclass方式实现单例模式
  • 相关阅读:
    QT学习笔记2
    QT学习笔记1
    图像中区域生长算法的详解和实现
    图像识别中的深度学习 转
    Appium基础环境搭建(windows)---基于python
    selenium实现文件上传方法汇总(AutoIt、win32GUI、sengkeys)---基于python
    selenium中的三种等待方式(显示等待WebDriverWait()、隐式等待implicitly()、强制等待sleep())---基于python
    水仙花数---基于python
    九九乘法表实现---基于python
    selenium元素定位不到之iframe---基于python
  • 原文地址:https://www.cnblogs.com/mengqingjian/p/8244530.html
Copyright © 2011-2022 走看看