python 常用的单例模式:模块 装饰器 元类

发布时间:2025-04-27      访问量:30
单例模式是一种设计模式,它确保一个类只有一个实例,并提供一个全局访问点来访问这个实例。在 Python 中,有多种实现单例模式的方法,下面为你介绍几种常用的实现方式。

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

总结
- **使用模块**:实现简单,适合全局配置等场景。
- **使用装饰器**:灵活,可以应用于多个类,代码复用性高。
- **使用元类**:更加底层,对类的创建过程有更多的控制权,适合复杂的场景。
堆内存
多线程
strdup
初始化器
冒泡排序
增删改查
BufferedReader
输入输出
面向对象
生命周期
闭包的概念
原型链
Flask
mysql-connector-python
单例模式
浅拷贝
隔离级别
索引
InnoDB
左连接
聚合函数
PuTTY
TRUNCATE
str_starts_with_many
DateTime
array_combine
闭包的概念