单例模式-python
单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在。当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场。
比如,某个服务器程序的配置信息存放在一个文件中,客户端通过一个 AppConfig 的类来读取配置文件的信息。如果在程序运行期间,有很多地方都需要使用配置文件的内容,也就是说,很多地方都需要创建 AppConfig 对象的实例,这就导致系统中存在多个 AppConfig 的实例对象,而这样会严重浪费内存资源,尤其是在配置文件内容很多的情况下。事实上,类似 AppConfig 这样的类,我们希望在程序运行期间只存在一个实例对象。
在 Python 中,我们可以用多种方法来实现单例模式:
- 使用模块
- 使用
__new__
- 使用装饰器(decorator)
- 使用元类(metaclass)
作为python的模块是天然的单例模式:
1 # mysingleton.py 2 class My_Singleton(object): 3 def foo(self): 4 pass 5 6 my_singleton = My_Singleton() 7 8 # to use 9 from mysingleton import my_singleton 10 11 my_singleton.foo()
使用__new__
方法
1 class Singleton(object): 2 def __new__(cls, *args, **kw): 3 if not hasattr(cls, '_instance'): 4 orig = super(Singleton, cls) 5 cls._instance = orig.__new__(cls, *args, **kw) 6 return cls._instance 7 8 class MyClass(Singleton): 9 a = 1
装饰器
1 def singleton(cls, *args, **kw): 2 instances = {} 3 def getinstance(): 4 if cls not in instances: 5 instances[cls] = cls(*args, **kw) 6 return instances[cls] 7 return getinstance 8 9 @singleton 10 class MyClass: 11 ...
元类
class Singleton1(type): _inst = {} def __call__(self, *args, **kw): if self not in self._inst: self._inst[self] = super(Singleton1, self).__call__(*args, **kw) return self._inst[self]