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

    所谓单例,是指一个类的实例从始至终只能被创建一次。以后调用只调用他一个

    ----类

    ----__new__

    ----元类metaclass

    ----文件

    import time
    import threading
    class Singleton(object):
        _instance_lock = threading.Lock()
    
        def __init__(self):
            time.sleep(1)
    
        @classmethod
        def instance(cls, *args, **kwargs):
            if not hasattr(Singleton, "_instance"):
                with Singleton._instance_lock:
                    if not hasattr(Singleton, "_instance"):
                        Singleton._instance = Singleton(*args, **kwargs)
            return Singleton._instance
    
    使用先说明,以后用单例模式,obj = Singleton.instance()
    示例:
    obj1 = Singleton.instance()
    obj2 = Singleton.instance()
    print(obj1,obj2)
    错误示例
    obj1 = Singleton()
    obj2 = Singleton()
    print(obj1,obj2)
    类(classmethod装饰器)
    import time
    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, *args, **kwargs)
            return Singleton._instance
    
    
    # 使用先说明,以后用单例模式,obj = Singleton()
    # 示例
    # obj1 = Singleton()
    # obj2 = Singleton()
    # print(obj1,obj2)
    __new__
    import threading
    
    class SingletonType(type):
        _instance_lock = threading.Lock()
        def __call__(cls, *args, **kwargs):
            if not hasattr(cls, "_instance"):
                with SingletonType._instance_lock:
                    if not hasattr(cls, "_instance"):
                        cls._instance = super(SingletonType,cls).__call__(*args, **kwargs)
            return cls._instance
    
    class Foo(metaclass=SingletonType):
        def __init__(self,name):
            self.name = name
    
    
    obj1 = Foo('name')
    obj2 = Foo('name')
    print(obj1,obj2)
    元类mateclass

    PS: 为了保证线程安全在内部加入锁

    其实,Python 的模块就是天然的单例模式,因为模块在第一次导入时,会生成 .pyc 文件,当第二次导入时,就会直接加载 .pyc 文件,而不会再次执行模块代码。因此,我们只需把相关的函数和数据定义在一个模块中,就可以获得一个单例对象了。如果我们真的想要一个单例类,可以考虑这样做:

    将上面的代码保存在文件 mysingleton.py 中,然后这样使用:

    from mysingleton import my_singleton
     
    my_singleton.foo()

    追加:

    最简单的方法:

    1
    2
    3
    class singleton(object):
        pass
    singleton=singleton()

    将名字singleton绑定到实例上,singleton就是它自己类的唯一对象了。

  • 相关阅读:
    MySQL 资源大全中文版
    Linux性能实时监测工具 Netdata
    《Linux大棚》博客
    GNU bash实现机制与源代码简析
    C#+ArcGIS Engine 获取地图中选中的要素
    arcgis engine 获取高亮Feature、element
    DotNetBar 源码与安装版本
    ArcGIS 按多边形区域统计栅格影像的一些信息
    ArcGIS 空间查询
    55.npm install 报错 :stack Error: Can't find Python executable "python"
  • 原文地址:https://www.cnblogs.com/yifugui/p/8243837.html
Copyright © 2011-2022 走看看