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

    基于 __new__实现单例模式

    import time
    import threading
    
    class Singleton(object):
        instance = None
        lock = threading.RLock()
        
        def __new__(cls, *arg, **kwargs):
            if cls.instance:
                return cls.instance
            with cls.lock:
                if not cls.instance:
                    cls.instance = object.__new__(cls)
                return cls.instance
            
    obj = Singleton()
    print(obj)
    

    基于文件导入实现单利模式

    # sg.py
    class Singleton(object):
        pass
    
    obj = Singleton()
    
    import sg
    print(sg.obj)
    

    应用场景:

    • django中settings配置文件
    • django的admin内部使用,将所有model类注册到了一个字典中。

    new`方法返回的是什么?

    新创建的对象,内部没有数据,需要经过init来进行初始化。
  • 相关阅读:
    sql推断时间
    COCOFrame
    第41周一
    第40周日
    第40周六
    第40周五
    第40周四
    第40周三国庆
    第40周二晚
    第40周二
  • 原文地址:https://www.cnblogs.com/lvweihe/p/12637760.html
Copyright © 2011-2022 走看看