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

    在python中,我们可以用多种方法来实现单例模式:

      - 使用模块

      - 使用__new__

      - 使用装饰器

      - 使用元类(metaclass)

    使用模块

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

    复制代码
    # mysingle.py
    class MySingle:
      def foo(self):
        pass

    sinleton = MySingle()
    将上面的代码保存在文件mysingle.py中,然后这样使用:
    from mysingle import sinleton
    singleton.foo()
    复制代码

    当我们实现单例时,为了保证线程安全需要在内部加入锁

    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

    使用__new__

    为了使类只能出现一个实例,我们可以使用__new__来控制实例的创建过程,代码如下:

    复制代码
    class Singleton(object):
        def __new__(cls):
            # 关键在于这,每一次实例化的时候,我们都只会返回这同一个instance对象
            if not hasattr(cls, 'instance'):
                cls.instance = super(Singleton, cls).__new__(cls)
            return cls.instance
     
    obj1 = Singleton()
    obj2 = Singleton()
     
    obj1.attr1 = 'value1'
    print obj1.attr1, obj2.attr1
    print obj1 is obj2
     
    输出结果:
    value1  value1
    复制代码

    使用装饰器:

    我们知道,装饰器可以动态的修改一个类或函数的功能。这里,我们也可以使用装饰器来装饰某个类,使其只能生成一个实例:

    复制代码
    def singleton(cls):
        instances = {}
        def getinstance(*args,**kwargs):
            if cls not in instances:
                instances[cls] = cls(*args,**kwargs)
            return instances[cls]
        return getinstance
    
    @singleton
    class MyClass:
        a = 1
    
    c1 = MyClass()
    c2 = MyClass()
    print(c1 == c2) # True


    在上面,我们定义了一个装饰器 singleton,它返回了一个内部函数 getinstance
    该函数会判断某个类是否在字典 instances 中,如果不存在,则会将 cls 作为 key,cls(*args, **kw) 作为 value 存到 instances 中,
    否则,直接返回 instances[cls]
    复制代码

    使用metaclass(元类)

    元类可以控制类的创建过程,它主要做三件事:

      - 拦截类的创建

      - 修改类的定义

      - 返回修改后的类

    使用元类实现单例模式:

    class Singleton2(type):
        def __init__(self, *args, **kwargs):
            self.__instance = None
            super(Singleton2,self).__init__(*args, **kwargs)
    
        def __call__(self, *args, **kwargs):
            if self.__instance is None:
                self.__instance = super(Singleton2,self).__call__(*args, **kwargs)
            return self.__instance
    
    
    class Foo(metaclass=Singleton2):
        pass   #在代码执行到这里的时候,元类中的__new__方法和__init__方法其实已经被执行了,而不是在Foo实例化的
    时候执行。且仅会执行一次。 foo1 = Foo() foo2 = Foo() print (Foo.__dict__) #_Singleton__instance': <__main__.Foo object at 0x100c52f10> 存在一个私有属性来保存属性,而不会污染
    Foo类(其实还是会污染,只是无法直接通过__instance属性访问) print (foo1 is foo2) # True
  • 相关阅读:
    Java中,由this关键字引发的问题
    Spring3.2.11与Quartz2.2.1整合时内存泄漏的问题的解决
    使用Nexus管理Maven仓库时,上传带依赖的第三方jar
    ActiveMQ5.10.2版本配置JMX
    JAVA的Hashtable在遍历时的迭代器线程问题
    关于JAVA中String类型的最大长度
    新增了某个模组后VS编译不过,报错说找不到头文件
    重写Overlap事件
    cmd端口占用查看和关闭端口
    转---详细的Android开发环境搭建教程
  • 原文地址:https://www.cnblogs.com/zhaopanpan/p/8910058.html
Copyright © 2011-2022 走看看