能不能用Singleton的设计模式来管理全局变量呢?
能不能用Singleton的设计模式来管理全局变量呢?
坑
这篇博客写的有水平,又形象,又准确,建议拿过来分享
https://refactoringguru.cn/design-patterns/singleton
但是还是没有解决这个问题,如何在Singleton类中放置全局变量,并提供访问
这篇博客讲的算是最详细的了。
http://www.10qianwan.com/articledetail/311125.html
需要我们了解:
dataclass 是什么东西?
config类一般最常用Singleton的设计模式了
-----先放弃吧,没有找到比较好的示例code
先用最原始的的管理方式吧
一个.py文件,里边直接塞全局变量吧
以下是我尝试的实践
#创建一个 Singleton 的全局类 class GlobalVar(object): __instance = None _global_dict = {} def __init__(self): if not GlobalVar.__instance: print('Instance does not exist...') else: print('Instance exists:', self.get_instance()) @classmethod def get_instance(cls): if not cls.__instance: cls.__instance = GlobalVar() return cls.__instance def set_value(cls,name, value): """定义一个全局变量""" GlobalVar.get_instance()._global_dict[name] = value def get_value(cls,name, defValue=None): """获取一个全局变量值,不能存在则返回默认值""" try: return GlobalVar.get_instance()._global_dict[name] except KeyError: return defValue if __name__ == "__main__": a = GlobalVar() # Once a singleton is created, all instances of this class will use the same object print('Creating instance', GlobalVar.get_instance()) # Since singleton already created, the existing object is returned b = GlobalVar() # Even though we now have 3 different instances of this class, they all reference the same object c = GlobalVar() a.set_value("rootpath", 'c:\s\d\d\e\s\e') print(b.get_value("rootpath")) print(GlobalVar().get_value("rootpath"))
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?