Python
单例模式(Singleton Pattern) 是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在。当希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场。
比如,某个服务器程序的配置信息存放在一个文件中,客户端通过一个 AppConfig 的类来读取配置文件的信息。如果在程序运行期间,有很多地方都需要使用配置文件的内容,也就是说,很多地方都需要创建 AppConfig 对象的实例,这就导致系统中存在多个 AppConfig 的实例对象,而这样会严重浪费内存资源,尤其是在配置文件内容很多的情况下。
事实上,类似 AppConfig 这样的类,希望在程序运行期间只存在一个实例对象。
在 Python 中,可以用多种方法来实现单例模式:

  1. 使用模块
  2. 使用装饰器
  3. 使用类
  4. 基于 __new__ 方法实现
  5. 基于 metaclass 方式实现

下面来详细介绍:

使用模块

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

  1. class Singleton(object):
  2. def foo(self):
  3. pass
  4. singleton = Singleton()

将上面的代码保存在文件 mysingleton.py 中,要使用时,直接在其他文件中导入此文件中的对象,这个对象即是单例模式的对象

  1. from mysingleton import singleton

使用装饰器

  1. def Singleton(cls):
  2. _instance = {}
  3. def _singleton(*args, **kargs):
  4. if cls not in _instance:
  5. _instance[cls] = cls(*args, **kargs)
  6. return _instance[cls]
  7. return _singleton
  8. @Singleton
  9. class A(object):
  10. a = 1
  11. def __init__(self, x=0):
  12. self.x = x
  13. a1 = A(2)
  14. a2 = A(3)

使用类

  1. class Singleton(object):
  2. def __init__(self):
  3. pass
  4. @classmethod
  5. def instance(cls, *args, **kwargs):
  6. if not hasattr(Singleton, "_instance"):
  7. Singleton._instance = Singleton(*args, **kwargs)
  8. return Singleton._instance

一般情况,大家以为这样就完成了单例模式,但是当使用多线程时会存在问题:

  1. class Singleton(object):
  2. def __init__(self):
  3. pass
  4. @classmethod
  5. def instance(cls, *args, **kwargs):
  6. if not hasattr(Singleton, "_instance"):
  7. Singleton._instance = Singleton(*args, **kwargs)
  8. return Singleton._instance
  9. import threading
  10. def task(arg):
  11. obj = Singleton.instance()
  12. print(obj)
  13. for i in range(10):
  14. t = threading.Thread(target=task,args=[i,])
  15. t.start()

程序执行后,打印结果如下:

  1. <__main__.Singleton object at 0x02C933D0>
  2. <__main__.Singleton object at 0x02C933D0>
  3. <__main__.Singleton object at 0x02C933D0>
  4. <__main__.Singleton object at 0x02C933D0>
  5. <__main__.Singleton object at 0x02C933D0>
  6. <__main__.Singleton object at 0x02C933D0>
  7. <__main__.Singleton object at 0x02C933D0>
  8. <__main__.Singleton object at 0x02C933D0>
  9. <__main__.Singleton object at 0x02C933D0>
  10. <__main__.Singleton object at 0x02C933D0>

看起来也没有问题,那是因为执行速度过快,如果在 __init__ 方法中有一些 IO 操作,就会发现问题了。
下面通过 time.sleep 模拟,在上面 __init__ 方法中加入以下代码:

  1. def __init__(self):
  2. import time
  3. time.sleep(1)

重新执行程序后,结果如下:

  1. <__main__.Singleton object at 0x034A3410>
  2. <__main__.Singleton object at 0x034BB990>
  3. <__main__.Singleton object at 0x034BB910>
  4. <__main__.Singleton object at 0x034ADED0>
  5. <__main__.Singleton object at 0x034E6BD0>
  6. <__main__.Singleton object at 0x034E6C10>
  7. <__main__.Singleton object at 0x034E6B90>
  8. <__main__.Singleton object at 0x034BBA30>
  9. <__main__.Singleton object at 0x034F6B90>
  10. <__main__.Singleton object at 0x034E6A90>

问题出现了!按照以上方式创建的单例,无法支持多线程。
解决办法:加锁!未加锁部分并发执行,加锁部分串行执行,速度降低,但是保证了数据安全。

  1. import time
  2. import threading
  3. class Singleton(object):
  4. _instance_lock = threading.Lock()
  5. def __init__(self):
  6. time.sleep(1)
  7. @classmethod
  8. def instance(cls, *args, **kwargs):
  9. with Singleton._instance_lock:
  10. if not hasattr(Singleton, "_instance"):
  11. Singleton._instance = Singleton(*args, **kwargs)
  12. return Singleton._instance
  13. def task(arg):
  14. obj = Singleton.instance()
  15. print(obj)
  16. for i in range(10):
  17. t = threading.Thread(target=task,args=[i,])
  18. t.start()
  19. time.sleep(20)
  20. obj = Singleton.instance()
  21. print(obj)

打印结果如下:

  1. <__main__.Singleton object at 0x02D6B110>
  2. <__main__.Singleton object at 0x02D6B110>
  3. <__main__.Singleton object at 0x02D6B110>
  4. <__main__.Singleton object at 0x02D6B110>
  5. <__main__.Singleton object at 0x02D6B110>
  6. <__main__.Singleton object at 0x02D6B110>
  7. <__main__.Singleton object at 0x02D6B110>
  8. <__main__.Singleton object at 0x02D6B110>
  9. <__main__.Singleton object at 0x02D6B110>
  10. <__main__.Singleton object at 0x02D6B110>

这样就差不多了,但是还是有一点小问题,就是当程序执行时,执行了 time.sleep(20) 后,下面实例化对象时,此时已经是单例模式了。
但还是加了锁,这样不太好,再进行一些优化,把 intance 方法,改成下面这样就行:

  1. @classmethod
  2. def instance(cls, *args, **kwargs):
  3. if not hasattr(Singleton, "_instance"):
  4. with Singleton._instance_lock:
  5. if not hasattr(Singleton, "_instance"):
  6. Singleton._instance = Singleton(*args, **kwargs)
  7. return Singleton._instance

这样,一个可以支持多线程的单例模式就完成了。+

  1. import time
  2. import threading
  3. class Singleton(object):
  4. _instance_lock = threading.Lock()
  5. def __init__(self):
  6. time.sleep(1)
  7. @classmethod
  8. def instance(cls, *args, **kwargs):
  9. if not hasattr(Singleton, "_instance"):
  10. with Singleton._instance_lock:
  11. if not hasattr(Singleton, "_instance"):
  12. Singleton._instance = Singleton(*args, **kwargs)
  13. return Singleton._instance
  14. def task(arg):
  15. obj = Singleton.instance()
  16. print(obj)
  17. for i in range(10):
  18. t = threading.Thread(target=task,args=[i,])
  19. t.start()
  20. time.sleep(20)
  21. obj = Singleton.instance()
  22. print(obj)

这种方式实现的单例模式,使用时会有限制,以后实例化必须通过 obj = Singleton.instance()
如果用 obj = Singleton(),这种方式得到的不是单例。

基于 __new__ 方法实现

通过上面例子,可以知道,当实现单例时,为了保证线程安全需要在内部加入锁。
当实例化一个对象时,是先执行了类的 __new__ 方法(没写时,默认调用 object.__new__),实例化对象;然后再执行类的 __init__ 方法,对这个对象进行初始化,所有可以基于这个,实现单例模式。

  1. import threading
  2. class Singleton(object):
  3. _instance_lock = threading.Lock()
  4. def __init__(self):
  5. pass
  6. def __new__(cls, *args, **kwargs):
  7. if not hasattr(Singleton, "_instance"):
  8. with Singleton._instance_lock:
  9. if not hasattr(Singleton, "_instance"):
  10. Singleton._instance = object.__new__(cls)
  11. return Singleton._instance
  12. obj1 = Singleton()
  13. obj2 = Singleton()
  14. print(obj1,obj2)
  15. def task(arg):
  16. obj = Singleton()
  17. print(obj)
  18. for i in range(10):
  19. t = threading.Thread(target=task,args=[i,])
  20. t.start()

打印结果如下:

  1. <__main__.Singleton object at 0x038B33D0> <__main__.Singleton object at 0x038B33D0>
  2. <__main__.Singleton object at 0x038B33D0>
  3. <__main__.Singleton object at 0x038B33D0>
  4. <__main__.Singleton object at 0x038B33D0>
  5. <__main__.Singleton object at 0x038B33D0>
  6. <__main__.Singleton object at 0x038B33D0>
  7. <__main__.Singleton object at 0x038B33D0>
  8. <__main__.Singleton object at 0x038B33D0>
  9. <__main__.Singleton object at 0x038B33D0>
  10. <__main__.Singleton object at 0x038B33D0>
  11. <__main__.Singleton object at 0x038B33D0>

采用这种方式的单例模式,以后实例化对象时,和平时实例化对象的方法一样 obj = Singleton() 。

基于 metaclass 方式实现

相关知识:

  1. 类由 type 创建,创建类时,type 的 __init__ 方法自动执行,类() 执行 type 的 __call__ 方法(类的 __new__ 方法,类的 __init__ 方法)
  2. 对象由类创建,创建对象时,类的 __init__ 方法自动执行,对象()执行类的 __call__ 方法

例子:

  1. class Foo:
  2. def __init__(self):
  3. pass
  4. def __call__(self, *args, **kwargs):
  5. pass
  6. obj = Foo()
  7. # 执行type的 __call__ 方法,调用 Foo类(是type的对象)的 __new__方法,用于创建对象,然后调用 Foo类(是type的对象)的 __init__方法,用于对对象初始化。
  8. obj() # 执行Foo的 __call__ 方法

元类的使用:

  1. class SingletonType(type):
  2. def __init__(self,*args,**kwargs):
  3. super(SingletonType,self).__init__(*args,**kwargs)
  4. def __call__(cls, *args, **kwargs): # 这里的cls,即Foo类
  5. print('cls',cls)
  6. obj = cls.__new__(cls,*args, **kwargs)
  7. cls.__init__(obj,*args, **kwargs) # Foo.__init__(obj)
  8. return obj
  9. class Foo(metaclass=SingletonType): # 指定创建Foo的type为SingletonType
  10. def __init__(self,name):
  11. self.name = name
  12. def __new__(cls, *args, **kwargs):
  13. return object.__new__(cls)
  14. obj = Foo('xx')

实现单例模式:

  1. import threading
  2. class SingletonType(type):
  3. _instance_lock = threading.Lock()
  4. def __call__(cls, *args, **kwargs):
  5. if not hasattr(cls, "_instance"):
  6. with SingletonType._instance_lock:
  7. if not hasattr(cls, "_instance"):
  8. cls._instance = super(SingletonType,cls).__call__(*args, **kwargs)
  9. return cls._instance
  10. class Foo(metaclass=SingletonType):
  11. def __init__(self,name):
  12. self.name = name
  13. obj1 = Foo('name')
  14. obj2 = Foo('name')
  15. print(obj1,obj2)