类似的问题已经被问过很多次了,但我还是很难理解。我在想Singleton或Borg模式只能用来创建一个对象的一个实例,或者共享它的状态。我有一个(正在工作的)测试示例,它并不像我期望的那样工作。要么代码不正确,要么我误解了singleton/borg模式的概念。在
我使用singleton和borg模式在文件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
最后是主要代码:
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
中添加的那样?我应该使用什么模式/机制来实现这一点?在
出现这种行为的原因是,在这两种情况下,
__init__
每次执行instance = WhateverClass()
时都会被调用。在请注意,您正在传递同一个实例。但是,该实例的
_list
属性在__init__
中被清除。在相关问题 更多 >
编程相关推荐