python的两种单例模式

基于模块的单例模式

在 Python 中,模块是天然的单例模式。因为模块在第一次导入时,会生成 .pyc 文件,当第二次导入时,会直接加载 .pyc 文件,而不会再次执行模块代码。因此,可以将相关的类和实例定义在一个模块中,通过导入模块来获取唯一的实例。

py 复制代码
# singleton_module.py
class SingletonClass:
    def __init__(self):
        self.value = 0

    def increment(self):
        self.value += 1

# 创建唯一的实例
singleton_instance = SingletonClass()

然后在另一个文件中使用这个单例实例:

py 复制代码
# main.py
from singleton_module import singleton_instance

# 第一次调用
print(singleton_instance.value)  # 输出 0
singleton_instance.increment()

# 再次调用
from singleton_module import singleton_instance
print(singleton_instance.value)  # 输出 1

在 singleton_module.py 中定义了一个 SingletonClass 类,并创建了该类的一个实例 singleton_instance

main.py 中,无论导入多少次 singleton_instance,获取的都是同一个实例,因此对实例的操作会保持状态

基于装饰器的单例模式

使用装饰器可以在不修改原类代码的情况下,将类转换为单例类。装饰器会维护一个字典,用于存储类和其对应的实例,当第一次调用被装饰的类创建实例时,会将该实例存储在字典中,后续再次调用时,直接从字典中获取已创建的实例。

py 复制代码
# 入参是一个类,出参是一个函数
def singleton_decorator(cls):
    instances = {}

    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]

    return get_instance

@singleton_decorator
class MySingleton:
    def __init__(self):
        self.value = 0

    def increment(self):
        self.value += 1

# 创建实例
instance1 = MySingleton()
instance2 = MySingleton()

print(instance1 is instance2)  # 输出 True,表示两个实例是同一个对象
instance1.increment()
print(instance2.value)  # 输出 1

代码解释

singleton_decorator 是一个装饰器函数,它接受一个类作为参数,并返回一个 get_instance 函数

instances 是一个字典,用于存储类和其对应的实例

get_instance 函数会检查 instances 字典中是否已经存在该类的实例,如果不存在则创建一个新实例并存储在字典中,然后返回该实例。

MySingleton 类被 singleton_decorator 装饰

每次创建 MySingleton 类的实例时,实际上都会返回同一个实例

优缺点

基于模块的方式简单直接,适合简单场景

基于装饰器的方式更加灵活,可以应用于多个不同的类

相关推荐
大模型真好玩18 分钟前
准确率飙升!GraphRAG如何利用知识图谱提升RAG答案质量(额外篇)——大规模文本数据下GraphRAG实战
人工智能·python·mcp
198919 分钟前
【零基础学AI】第30讲:生成对抗网络(GAN)实战 - 手写数字生成
人工智能·python·深度学习·神经网络·机器学习·生成对抗网络·近邻算法
applebomb29 分钟前
没合适的组合wheel包,就自行编译flash_attn吧
python·ubuntu·attention·flash
Chasing__Dreams1 小时前
python--杂识--18.1--pandas数据插入sqlite并进行查询
python·sqlite·pandas
彭泽布衣2 小时前
python2.7/lib-dynload/_ssl.so: undefined symbol: sk_pop_free
python·sk_pop_free
喜欢吃豆2 小时前
从零构建MCP服务器:FastMCP实战指南
运维·服务器·人工智能·python·大模型·mcp
一个处女座的测试3 小时前
Python语言+pytest框架+allure报告+log日志+yaml文件+mysql断言实现接口自动化框架
python·mysql·pytest
nananaij3 小时前
【Python基础入门 re模块实现正则表达式操作】
开发语言·python·正则表达式
蛋仔聊测试3 小时前
Playwright 网络流量监控与修改指南
python
nightunderblackcat4 小时前
进阶向:Python音频录制与分析系统详解,从原理到实践
开发语言·python·音视频