zoukankan      html  css  js  c++  java
  • python singleton 4种单例

    def singleton(cls, *args, **kwargs):
        instances = {}
        def inner(cls, *args, **kwargs):
            if cls not in instances:
                instances[cls] = cls(*args, **kwargs)
            return instances[cls]
        return inner
    
    @singleton
    class Test1:
        pass
    
    # 推荐使用这种 简单好用 线程安全
    # ===========================================================
    import threading
    
    
    class Singleton:
        
        def __init__(self, cls):
            self.__cls = cls
            self.__instance = None
            self._lock = threading.Lock()
    
        def __call__(self, *args, **kwargs):
            self._lock.acquire()
            if self.__instance is None:
                self.__instance = self.__cls(*args, **kwargs)
            self._lock.release()
            return self.__instance
                
    
    @Singleton
    class Test2:
        pass
    
    
    # 继承时的执行顺序 base new -> son new -> son init. new 相当于构造方法,init相当于实例后再初始化 先执行父类的new 就好比先是人再是学生
    # ==============================================================
    class SingleBase(object):
        instance = None
        
        def __new__(cls, *args, **kwargs):
    
            # if not instance:
            #     instance = cls.__new__(*args, **kwargs):
            # return instance
            if cls.instance is None:
                cls.instance = object.__new__(cls)
            return cls.instance
    
        def __init__(self):
            pass
    
    
    class Test3(SingleBase):
        
        def __init__(self, name):
            self._name = name
    
        def get_name(self):
            return self._name
    
    
    # meta 这个我还不是很懂
    # =====================================================
    class MetaSingleton(type):
        _instances = {}
        def __call__(cls, *args, **kwargs):
            if cls not in cls._instances:
                cls._instances[cls] = super().__call__(*args, **kwargs)
            return cls._instances[cls]
    
    class Test4(metaclass=MetaSingleton):
        
        def __init__(self):
            pass
    
    if __name__ == '__main__':
        t1 = Test3('jwang')
        t2 = Test3('hello')
        print(id(t1))
        print(id(t2))
        print(t1.get_name())
        print(t2.get_name())
    
        test3 = Test4()
        test4 = Test4()
        print(id(test3) == id(test4))
    
    
  • 相关阅读:
    产生财务计帐周期
    判断指定年份是否为闰年
    判断是否是闰年
    Regex quick reference
    组合外键(FOREIGN KEY)
    多列组合为主键(PRIMARY KEY)
    获取字符串开始的地址(案例)
    获取字符串结尾的电话号码(案例)
    ms sql server line feed
    如何产生连续时间?(案例)
  • 原文地址:https://www.cnblogs.com/wangjiale1024/p/11329493.html
Copyright © 2011-2022 走看看