Python单体模式的几种常见实现方法详解
本文详细解析Python中实现单体模式的多种技巧,包括修改父类__dict__的Borg模式、基于元类的__call__与__new__实现,以及利用类方法__new__和classmethod的巧妙方案。重点对比各方法的适用场景与参数细节,帮助开发者根据实际需求选择正确的单体实现路径。
本文介绍了Python中实现单体模式的几种主流方案,旨在为读者提供实用的参考代码与思路。
文中部分实现思路参考了StackOverflow上的讨论:https://stackoverflow.com/questions/1363839/python-singleton-object-instantiation/1363852#1363852
一、通过修改父类的 __dict__ 属性
class Borg:
_shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
class Singleton(Borg):
def __init__(self, name):
super().__init__()
self.name = name
def __str__(self):
return self.name
x = Singleton('sausage')
print(x)
y = Singleton('eggs')
print(y)
z = Singleton('spam')
print(z)
print(x)
print(y)
需要指出的是,这种实现方式并非严格意义上的单体模式。
接下来的几种方法则能实现真正的单体模式。
二、利用元类(Metaclass)实现
首先回顾一下元类的相关概念:
元类通常用于控制类的创建过程。
在定义类时,Python解释器需要确定该类使用的元类。解释器会优先查找类属性 __metaclass__,若存在则将其设为该类的元类;若未定义,则向上查找父类的 __metaclass__;若仍未找到 __metaclass__,则检查全局变量 __metaclass__;若以上均不存在,默认使用内置的 type 作为元类。
1. 继承 type,并重写 __call__ 方法
请注意 __call__ 方法的参数定义。
class Singleton(type):
_instance = None
def __call__(self, *args, **kw):
if self._instance is None:
self._instance = super().__call__(*args, **kw)
return self._instance
class MyClass(object):
__metaclass__ = Singleton
print(MyClass())
print(MyClass())
2. 继承 type,并重写 __new__ 方法
请注意 __new__ 方法的参数定义。
class Singleton(type):
_instance = None
def __new__(cls, name, bases, dct):
if cls._instance is None:
cls._instance = super().__new__(cls, name, bases, dct)
return cls._instance
class MyClass(object):
__metaclass__ = Singleton
print(MyClass())
print(MyClass())
3. 继承 object,并重写 __new__ 方法
请注意 __new__ 方法的参数定义。
class Singleton(object):
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
class MyClass(object):
__metaclass__ = Singleton
print(MyClass())
print(MyClass())
此外,还有一种较为巧妙的单体模式实现方式。
利用类方法 classmethod 进行控制
class Singleton:
_instance = None
@classmethod
def create(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance
def __init__(self):
self.x = 5 # or whatever you want to do
sing = Singleton.create()
print(sing.x) # 5
sec = Singleton.create()
print(sec.x) # 5
如需了解更多Python相关知识,可参考本站系列教程:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》以及《Python入门与进阶经典教程》。
希望上述内容能对您的Python编程实践有所帮助。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









