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

    #单例模式(不支持多线程)
    import threading
    
    class Single():
        f=None
        lock=threading.Lock()
    
        def __init__(self):
            pass
    
        def __new__(cls,*args,**kw):
            if Single.f==None:
                with Single.lock:  #加锁,防止多线程并发
                    if Single.f==None:
                        Single.f=object.__init__(cls)
            return Single.f
        
    s1=Single()
    s2=Single()
    print(id(s1))
    print(id(s2))
    class Single(object):
        def __new__(cls, *args, **kwargs):
            if not hasattr(cls,'_instance'):
                cls._instance=object.__new__(cls)
            return cls._instance
        def __init__(self,a,b):
            self.a=a
            self.b=b
    
    class Single11(object):
        def __new__(cls, *args, **kwargs):
            if not hasattr(cls,'_instance'):
                cls._instance=super().__init__(cls)
            return cls._instance
    
    if __name__=='__main__':
        s=Single11(1,2)
        ss=Single11(1,2)
        print(id(s)==id(ss))

     2、父类继承初始化 __init__()

    class Father():
        def __init__(self,a,b):
            self.a=a
            self.b=b
    
        def getA(self):
            return self.a
    
        def getB(self):
            return self.b
    
    class Son(Father):
        def __init__(self,name,age,a,b):
            # Father.__init__(self,a,b)  #经典类的调用父类方式
            #super().__init__(a,b)       #新式类
            super(Son,self).__init__(a,b)#新式类
    
            self.name=name
            self.age=age
    
        def getInfo(self):
            print(self.name,self.age,self.a,self.b)
    
    import threading
    class Single():
        lock=threading.Lock()
        def __init__(self):
            pass
        def __new__(cls, *args, **kwargs):
            with Single.lock:                         #不确认这个方式是否可行,限制多线程
                if not hasattr(cls,"_instance"):
                    cls._instance=object.__new__(cls)
            return cls._instance
    
    class Singleton():
        def __init__(self,a,b):
            self.a=a
            self.b=b
    
        def __new__(cls, *args, **kwargs):
            if not hasattr(cls,"_instance"):
                #cls._instance=super().__new__(cls)  #三种方式调用父类的__new__
                #cls._instance=object.__new__(cls)
                cls._instance = super(Singleton,cls).__new__(cls)
            return cls._instance     
  • 相关阅读:
    23种设计模式之责任链模式
    23种设计模式之中介者模式
    23种设计模式之代理模式
    23种设计模式之原型模式
    23种设计模式之模板方法模式
    23种设计模式之建造者模式
    23中设计模式之抽象工厂模式
    批处理产生001到999之间的数字
    批处理随机显示星期几
    批处理简易密码登录
  • 原文地址:https://www.cnblogs.com/xiaoxiao075/p/10497640.html
Copyright © 2011-2022 走看看