竞争无处不在,青春永不言败!专业撸代码,副业修bug

Talk is cheap , show me the code!



python 单例模式总结

参考

# 第一种方法 new 方法
class Singleton(object):
    def __new__(cls,*args,**kw):
        if not hasattr(cls,'_instance'):
            cls._instance = super(Singleton,cls).__new__(cls,*args,**kw)
        return cls._instance
    
s1 = Singleton()
s2 = Singleton()
s1 == s2
# 第二种方法升级为元类 call 控制,实质跟方法一差不多
class SingletonMetaclass(type):    
    def __call__(cls,*args,**kw):
        if not hasattr(cls,'_instance'):
            cls._instance = super(SingletonMetaclass,cls).__call__(*args,**kw)
#         cls.__init__(cls._instance,*args,**kw)
        return cls._instance
        
class Singleton(object,metaclass=SingletonMetaclass):
    pass
    
s1 = Singleton()
s2 = Singleton()
s1 == s2
# 第三种,使用装饰器
def singleton(cls,*args,**kw):
    instance = {}
    def get_instance():
        if cls not in instance:
            instance[cls] = cls.__new__(cls,*args,**kw)
        return instance[cls]
    return get_instance

@singleton
class Singleton(object):
    pass

s1 = Singleton()
s2 = Singleton()
s1 == s2

线程安全

# 线程安全的 写法
# 装饰器
import threading
def Singleton(cls,*args,**kw):
    instance = {}
    _instance_lock = threading.Lock()
    def get_instance():
        if cls not in instance:
            with _instance_lock:
                if cls not in instance:
                    instance[cls] = cls.__new__(cls,*args,**kw)
                    cls.__init__(instance[cls],*args,**kw)
        return instance[cls]
    return get_instance

@Singleton
class Demo(object):
    pass
d1 = Demo()
d2 = Demo()
d1 is d2
# 基类
class Singleton(object):
    def __new__(cls,*args,**kw):
        if not hasattr(cls,'_instance'):
                cls._instance = super(Singleton,cls).__new__(cls,*args,**kw)
        return cls._instance
    
s1 = Singleton()
s2 = Singleton()
print(s1 == s2)
# 升级为元类
import threading
class SingletonMetaclass(type):
    def __call__(cls,*args,**kw):
        _instance_lock = threading.Lock()
        if not hasattr(cls,'_instance'):
            with _instance_lock:
                if not hasattr(cls,'_instance'):
                    cls._instance = cls.__new__(cls,*args,**kw)
                    cls.__init__(cls._instance,*args,**kw)
        return cls._instance
    
class Demo(object,metaclass=SingletonMetaclass):
    pass

d2 = Demo()
d3 = Demo()
d2 is d3
mysingleton.py

class Singleton(object):
    def foo(self):
        pass
singleton = Singleton()
将上面的代码保存在文件 mysingleton.py 中,要使用时,直接在其他文件中导入此文件中的对象,这个对象即是单例模式的对象

from mysingleton import singleton
方法四:Borg模式
利用“类变量对所有对象唯一”,即__share_state

class Foo:
   __share_state = {}
   def __init__(self):
       self.__dict__ = self.__share_state
posted @ 2018-07-23 18:04  云雾散人  阅读(234)  评论(0编辑  收藏  举报

Your attitude not your aptitude will determine your altitude!

如果有来生,一个人去远行,看不同的风景,感受生命的活力!