Pyhton Singleton模式

本文介绍了一种使用装饰器而非元类实现Python单例模式的方法。该方法限制较少且易于实现,但装饰后的类不能被继承。通过示例展示了如何正确获取单例实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


class Singleton:
	"""
	A non-thread-safe helper class to ease implementing singletons.
	This should be used as a decorator -- not a metaclass -- to the
	class that should be a singleton.

	The decorated class can define one `__init__` function that
	takes only the `self` argument. Other than that, there are
	no restrictions that apply to the decorated class.

	To get the singleton instance, use the `Instance` method. Trying
	to use `__call__` will result in a `TypeError` being raised.

	Limitations: The decorated class cannot be inherited from.

	"""

	def __init__(self, decorated):
		self._decorated = decorated

	def Instance(self):
		"""
		Returns the singleton instance. Upon its first call, it creates a
		new instance of the decorated class and calls its `__init__` method.
		On all subsequent calls, the already created instance is returned.

		"""
		try:
			return self._instance
		except AttributeError:
			self._instance = self._decorated()
			return self._instance

	def __call__(self):
		raise TypeError('Singletons must be accessed through `Instance()`.')

	def __instancecheck__(self, inst):
		return isinstance(inst, self._decorated)
示例
 @Singleton
   class Foo:
       def __init__(self):
           print 'Foo created'

   f = Foo() # Error, this isn't how you get the instance of a singleton

   f = Foo.Instance() # Good. Being explicit is in line with the Python Zen
   g = Foo.Instance() # Returns already created instance

   print f is g # True
原文地址: http://stackoverflow.com/questions/42558/python-and-the-singleton-pattern

### Python 中实现 Singleton 模式的多种方法 #### 方法一:基于模块的单例模式 由于 Python 的模块本身具有单例性质,即每次导入同一个模块时只会在内存中加载一次。因此可以直接创建一个模块文件 `singleton.py` 来定义全局唯一实例。 ```python # singleton.py 文件内容如下: class _Singleton: def __init__(self): self.value = "This is a singleton" _singleton_instance = _Singleton() def get_instance(): return _singleton_instance ``` 通过上述方式,任何地方只要引入此模块并调用 `get_instance()` 函数即可获得相同的 `_Singleton` 实例[^1]。 #### 方法二:重写 `__new__` 构造器 另一种常见的做法是在类内部覆盖默认的 `__new__` 方法来控制对象的创建过程,从而确保整个程序运行期间只有一个实例存在。 ```python class Singleton(object): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs) return cls._instance ``` 这种方法能够有效防止多次实例化带来的资源浪费问题,并且保持了面向对象编程的良好习惯[^2]。 然而需要注意的是,如果开发者不小心操作的话可能会破坏这种机制,比如直接访问私有属性 `_instance` 并对其进行赋值或删除操作[^4]。 #### 方法三:装饰器版本 还可以采用函数装饰器的方式来简化单例模式的应用逻辑,使得其他普通类也能轻松转换成单例形式而无需改动原有结构。 ```python def singleton(cls): instances = {} def wrapper(*args, **kwds): if cls not in instances: instances[cls] = cls(*args, **kwds) return instances[cls] return wrapper @singleton class MyClass: pass ``` 当应用此类装饰器后,无论怎样尝试初始化新的 `MyClass` 对象,最终获取到的始终会是指向同一地址的对象引用[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值