1. 使用模块
在 Python 中,模块天然就是单例的。当一个模块被导入时,Python 会执行该模块的代码,并将其存储在内存中。后续再次导入该模块时,Python 会直接返回之前已经加载的模块对象,而不会重新执行模块代码。
main.py
from singleton_module import singleton_instance
#使用单例实例
singleton_instance.increment()
print(singleton_instance.value)
from singleton_module import singleton_instance as another_instance
another_instance.increment()
print(another_instance.value)
singleton_module.py
class Singleton:
def __init__(self):
self.value = 0
def increment(self):
self.value += 1
#创建单例实例
singleton_instance = Singleton()
2. 使用装饰器
可以使用装饰器来实现单例模式。装饰器会在类创建实例时进行检查,如果实例已经存在,则返回已有的实例,否则创建一个新的实例。
main_decorator.py
from singleton_decorator import MySingleton
#使用单例实例
instance1 = MySingleton()
instance1.increment()
print(instance1.value)
instance2 = MySingleton()
instance2.increment()
print(instance2.value)
singleton_decorator.py
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 MySingleton:
def __init__(self):
self.value = 0
def increment(self):
self.value += 1
3. 使用元类
元类是创建类的类。可以通过自定义元类来实现单例模式,在元类中控制类的实例化过程,确保类只有一个实例。
main_metaclass.py
from singleton_metaclass import MySingleton
使用单例实例
instance1 = MySingleton()
instance1.increment()
print(instance1.value)
instance2 = MySingleton()
instance2.increment()
print(instance2.value)
singleton_metaclass.py
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class MySingleton(metaclass=SingletonMeta):
def __init__(self):
self.value = 0
def increment(self):
self.value += 1
总结
- **使用模块**:实现简单,适合全局配置等场景。
- **使用装饰器**:灵活,可以应用于多个类,代码复用性高。
- **使用元类**:更加底层,对类的创建过程有更多的控制权,适合复杂的场景。