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()
 

使用__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
 

使用装饰器:

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

    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(object):
    __metaclass__ = Singleton2 #在代码执行到这里的时候,元类中的__new__方法和__init__方法其实已经被执行了,而不是在Foo实例化的时候执行。且仅会执行一次。


foo1 = Foo()
foo2 = Foo()
print (Foo.__dict__)  #_Singleton__instance': <__main__.Foo object at 0x100c52f10> 存在一个私有属性来保存属性,而不会污染Foo类(其实还是会污染,只是无法直接通过__instance属性访问)

print (foo1 is foo2)  # True
 

  - 使用模块

  - 使用__new__

  - 使用装饰器

  - 使用元类(metaclass)

使用模块

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

 
# mysingle.py
class MySingle:
  def foo(self):
    pass

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

使用__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
 

使用装饰器:

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

    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(object):
    __metaclass__ = Singleton2 #在代码执行到这里的时候,元类中的__new__方法和__init__方法其实已经被执行了,而不是在Foo实例化的时候执行。且仅会执行一次。


foo1 = Foo()
foo2 = Foo()
print (Foo.__dict__)  #_Singleton__instance': <__main__.Foo object at 0x100c52f10> 存在一个私有属性来保存属性,而不会污染Foo类(其实还是会污染,只是无法直接通过__instance属性访问)

print (foo1 is foo2)  # True
 

猜你喜欢

转载自www.cnblogs.com/weihengblog/p/9119226.html