当IT技术总监面试问:如何在Python中实现单例模式,并给出至少两种实现方法?

单例模式是一种确保一个类只有一个实例,并提供一个全局访问点的设计模式。以下是两种在Python中实现单例模式的方法:

方法1:使用模块
Python模块本身就是一个天然的单例,因为它们在第一次导入时被初始化,在后续导入时直接返回已创建的模块对象。

```python
# singleton.py
class Singleton:
    def __init__(self):
        self.value = None

    def set_value(self, value):
        self.value = value

    def get_value(self):
        return self.value
```

使用时:

```python
# main.py
from singleton import Singleton

# 获取单例对象
singleton_instance = Singleton()
singleton_instance.set_value("Kimi")

# 再次导入时,singleton_instance 仍然是同一个实例
from singleton import Singleton
another_instance = Singleton()
print(another_instance.get_value())  # 输出: Kimi
```

猜你喜欢

转载自blog.csdn.net/guo162308/article/details/143467038