什么是单胎/博格模式?为什么他们不为我工作/我的概念哪里错了?

2024-10-03 23:23:36 发布

您现在位置:Python中文网/ 问答频道 /正文

类似的问题已经被问过很多次了,但我还是很难理解。我在想Singleton或Borg模式只能用来创建一个对象的一个实例,或者共享它的状态。我有一个(正在工作的)测试示例,它并不像我期望的那样工作。要么代码不正确,要么我误解了singleton/borg模式的概念。在

我使用singletonborg模式在文件borg.py中创建以下代码:

class Singleton(object):
  _instance = None
  def __new__(class_, *args, **kwargs):
    if not isinstance(class_._instance, class_):
        class_._instance = object.__new__(class_, *args, **kwargs)
    return class_._instance



class MySingleton(Singleton):

    def __init__(self):
        self._list = []

    def add(self,x):
        self._list.append(x)

    def get(self):
        return self._list

class MyBorg(object):
    __shared_state = {}
    def __init__(self):
        self.__dict__ = self.__shared_state
        # and whatever else you want in your class -- that's all!
        self._list = []

    def add(self,x):
        self._list.append(x)

    def get(self):
        return self._list

然后是一个文件module.py

^{pr2}$

最后是主要代码:

from borg import MyBorg
import module
myborg = MyBorg()
myborg.add(4711)
print myborg.get()

在后两个类中,应该用MyBorg替换MySingleton,以使用Singleton而不是borg。在

现在,当我运行主代码时,我可以清楚地看到首先调用了modules.py,向列表中添加了一个值。之后,Singleton/Borg模式也会在主代码中实例化,并添加(另一个)值。我希望在列表中有两个值(42和4711),但是列表中只有后一个值。在

可能是module.py中的实例超出了范围,因此module.py中所做的一切都被删除了。但我需要的是有一个对象包含相同的内容,无论我在哪里使用它。在

我怎样才能做到这一点?我怎样才能确保,当我创建对象MyBorg的实例(或其他任何对象)时,它在列表中包含值'42',就像在module.py中添加的那样?我应该使用什么模式/机制来实现这一点?在


Tags: 对象实例instance代码pyself列表def
1条回答
网友
1楼 · 发布于 2024-10-03 23:23:36

出现这种行为的原因是,在这两种情况下,__init__每次执行instance = WhateverClass()时都会被调用。在

请注意,您正在传递同一个实例。但是,该实例的_list属性在__init__中被清除。在

class Singleton(object):
    _instance = None
    def __new__(class_, *args, **kwargs):
        if not isinstance(class_._instance, class_):
            class_._instance = object.__new__(class_, *args, **kwargs)
            return class_._instance

class Foo(Singleton):
    def __init__(self):
        self.data = []
    pass

a = Foo()
a.data.append('Never see this')
b = Foo()
print a is b  #True
print a.data  # []

相关问题 更多 >