使用Python实现单例模式
在Python中实现单例模式有多种方法,下面给出两种常见的方法。
1. 使用模块级别的变量:
python
class Singleton:
"""单例类"""
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super().__new__(cls, *args, **kwargs)
return cls._instance
# 使用示例
obj1 = Singleton()
obj2 = Singleton()
print(obj1 is obj2) # True
2. 使用装饰器:
python
def singleton(cls):
instances = {}
def wrapper(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return wrapper
@singleton
class Singleton:
"""单例类"""
pass
# 使用示例
obj1 = Singleton()
obj2 = Singleton()
print(obj1 is obj2) # True
以上两种方法都可以实现单例模式,保证在程序中只有一个实例。实现原理是通过重写`__new__`方法,控制实例化过程,确保只有一个实例被创建。