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

    Python 单例模式实现方法

    1.模块化

    # Python 的模块天然就是单例模式
    # 模块在第一次被导入时会生成.pyc文件,第二次导入时会直接加载.pyc文件 而不会再次执行模块中的的代码,所以我们可以这样来实现单例模式
    
    # test.py
    class A(object):
        def __init__(self, name):
            self.name = name
    t = A(treasure)
    
    # test1.py 
    from test import t # 这里引入的就是我们单例模式的对象
    

    2.使用装饰器

    def test(cls):
        _instance = {}
    
        def _sing(*args, **kwargs):
            if cls not in _instance:
                _instance[cls] = cls(*args, **kwargs)
            return _instance[cls]
        return _sing
    
    @test
    class A(object):
    
        a = 1
    
        def __init__(self, x):
            self.x = x
    
    a1 = A(2)
    a2 = A(3)
    
    # 打印可知a1, a2 两个对象的内存地址是一样的, 并且a2.x为2
    

    3.基于 _new__方法

    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)  
            return Singleton._instance
    
    obj1 = Singleton()
    obj2 = Singleton()
    print(obj1,obj2)
    
  • 相关阅读:
    33. 搜索旋转排序数组
    54. 螺旋矩阵
    46. 全排列
    120. 三角形最小路径和
    338. 比特位计数
    746. 使用最小花费爬楼梯
    spring boot的一些常用注解
    SSM整合Dubbo案例
    一些面试题
    Spring Aop和Spring Ioc(二)
  • 原文地址:https://www.cnblogs.com/Treasuremy/p/10402664.html
Copyright © 2011-2022 走看看