能不能用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"))

 

posted @ 2020-03-23 10:53  bH1pJ  阅读(14)  评论(0编辑  收藏  举报