博格设计模式

时间:2016-01-02 17:57:03

标签: python oop design-patterns

我正在尝试用Python学习设计模式。实现全局变量的推荐方法是通过Borg模式。

class Borg:
    __shared_state = {}
    def __init__(self):
        self.__dict__ = self.__shared_state

这似乎是一本字典。我将如何存储更复杂的数据结构,比如Pandas数据帧或自定义类,供全局使用?

2 个答案:

答案 0 :(得分:4)

实际上,这是推荐的方法,我从未在实际代码中看到过它。

推荐的方法是使用模块作为模块已经具有"全局"名称空间(有关globals()locals()vars())的详情,请参阅this answer

然而,为了理解:

到目前为止,您只是实例级别共享状态的基本框架。您现在需要的是您想要跟踪的其他州:

class Config(Borg):

    def __init__(self, config_file):
        super(Config, self).__init__()
        # load and parse file, saving settings to `self`

这种方法的一个缺点是你可能有几个消耗内存的实例都知道同样的事情。 (记忆不多,真的。)

实现共享状态的另一种方法"是只创建一个实例,然后让该类始终返回相同的实例 - 也称为singleton

class Config(object):

    the_one = None

    def __new__(cls, config):
        if cls.the_one is None:
            cls.the_one = Super(Config, cls).__new__(cls)
            # load and parse file, saving settings to `cls.the_one`
        return cls.the_one

任何一种方法都会产生以下结果:

>>> config = Config('my_config_file.cfg')
>>> config.screen_size
# whatever was saved during the loading and parsing of the config file
# for 'screen_size'

答案 1 :(得分:2)

这是推荐:

.fb_iframe_widget {
    display: inline-block;
    position: relative;
    vertical-align: middle;
    top: -2px;
}

#twitter-widget-0 {
    display: inline-block;
    vertical-align: middle;
}

完全不需要具有相同class Borg: __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state # *** 的不同对象。在这里,您可以使每个实例保持完全相同的数据。您也可以将对象设为单例,并避免创建冗余对象:

__dict__

但为什么要这样做呢?模块本质上是具有命名空间的单例,您可以在其中存储数据和功能。

我只想使用一个模块。

  

我如何存储更复杂的数据结构,比如Pandas数据框或自定义类,供全球使用?

简单 - 将数据存储在模块的全局变量中(例如class Borg(object): instance = None def __new__(cls): if cls.instance is None: cls.instance = super(Borg, cls).__new__(cls) return cls.instance >>> b1 = Borg() >>> b2 = Borg() >>> b1 is b2 True ),如下所示:

module.py

global_dataframe = pandas.DataFrame() class CustomClass: """my Python class definition""" global_dataframe现在都是模块级全局变量。您可以导入它们所在的模块,并通过虚线查找引用它们。

CustomClass
相关问题