单例模式:保证了所有的实例都指向一个类,唯一的内存空间。兄弟类不共享单一类。
例1:
class Singleton(object):
_instance = None
def __new__(cls):
if cls._instance == None:
cls._instance = object.__new__(cls)
return cls._instance
borg模式:一个实例改变,会影响到所有实例,在他们各自的内存空间传播。同时会影响到他们的兄弟类。
例子1:
class Borg(object):
_shared_state={}
def __init__(self):
self.__dict__ = self.__shared_state
例子2:
class Borg(object):
_we_are_one = {}
_myvalue = ""
def __new__(cls, *p, **k):
self = object.__new__(cls, *p, **k)
self.__dict__ = cls._we_are_one
return self
def myvalue(self, value=None):
if value:
self._myvalue = value
return self._myvalue
if __name__ == '__main__':
borg1 = Borg()
borg1.myvalue("Hello")
borg2 = Borg()
print borg2.myvalue() ## Hello