python 单列模式
时间: 2023-10-20 11:36:38 浏览: 47
单例模式是一种设计模式,用于确保一个类只有一个实例,并提供全局访问点。在 Python 中,可以通过多种方式实现单例模式。
一种常见的实现方式是使用装饰器,如下所示:
```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 MySingletonClass:
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
# 创建单例对象
obj1 = MySingletonClass("Hello", "World")
obj2 = MySingletonClass("Foo", "Bar")
# obj1 和 obj2 实际上是同一个对象
print(obj1 is obj2) # 输出: True
```
在上述示例中,`singleton` 是一个装饰器函数,用于将被修饰的类转换为单例类。通过 `@singleton` 注解,我们可以方便地将一个类转换为单例类。
还有其他实现单例模式的方式,比如使用元类、模块级别的变量等。具体选择哪种方式取决于使用场景和个人喜好。