3 回答
TA贡献1824条经验 获得超6个赞
博格与众不同的真正原因归结为子类化。
如果将borg子类化,则子类的对象与其父类对象具有相同的状态,除非您显式覆盖该子类中的共享状态。单例模式的每个子类都有其自己的状态,因此将产生不同的对象。
同样在单例模式中,对象实际上是相同的,而不仅仅是状态(即使状态是唯一真正重要的东西)。
TA贡献1779条经验 获得超6个赞
在python中,如果想要一个可以从任何地方访问的唯一“对象”,只需创建一个Unique仅包含静态属性@staticmethods和@classmethods的类;您可以将其称为唯一模式。在这里,我实现并比较3种模式:
独特
#Unique Pattern
class Unique:
#Define some static variables here
x = 1
@classmethod
def init(cls):
#Define any computation performed when assigning to a "new" object
return cls
辛格尔顿
#Singleton Pattern
class Singleton:
__single = None
def __init__(self):
if not Singleton.__single:
#Your definitions here
self.x = 1
else:
raise RuntimeError('A Singleton already exists')
@classmethod
def getInstance(cls):
if not cls.__single:
cls.__single = Singleton()
return cls.__single
博格
#Borg Pattern
class Borg:
__monostate = None
def __init__(self):
if not Borg.__monostate:
Borg.__monostate = self.__dict__
#Your definitions here
self.x = 1
else:
self.__dict__ = Borg.__monostate
测试
#SINGLETON
print "\nSINGLETON\n"
A = Singleton.getInstance()
B = Singleton.getInstance()
print "At first B.x = {} and A.x = {}".format(B.x,A.x)
A.x = 2
print "After A.x = 2"
print "Now both B.x = {} and A.x = {}\n".format(B.x,A.x)
print "Are A and B the same object? Answer: {}".format(id(A)==id(B))
#BORG
print "\nBORG\n"
A = Borg()
B = Borg()
print "At first B.x = {} and A.x = {}".format(B.x,A.x)
A.x = 2
print "After A.x = 2"
print "Now both B.x = {} and A.x = {}\n".format(B.x,A.x)
print "Are A and B the same object? Answer: {}".format(id(A)==id(B))
#UNIQUE
print "\nUNIQUE\n"
A = Unique.init()
B = Unique.init()
print "At first B.x = {} and A.x = {}".format(B.x,A.x)
A.x = 2
print "After A.x = 2"
print "Now both B.x = {} and A.x = {}\n".format(B.x,A.x)
print "Are A and B the same object? Answer: {}".format(id(A)==id(B))
输出:
辛格尔顿
At first B.x = 1 and A.x = 1
After A.x = 2
Now both B.x = 2 and A.x = 2
Are A and B the same object? Answer: True
BORG
At first B.x = 1 and A.x = 1
After A.x = 2
Now both B.x = 2 and A.x = 2
Are A and B the same object? Answer: False
UNIQUE
At first B.x = 1 and A.x = 1
After A.x = 2
Now both B.x = 2 and A.x = 2
Are A and B the same object? Answer: True
在我看来,唯一实现是最简单的,其次是Borg,最后是Singleton,其定义所需的两个函数数量很少。
TA贡献1821条经验 获得超4个赞
它不是。通常不建议在python中使用以下模式:
class Singleton(object):
_instance = None
def __init__(self, ...):
...
@classmethod
def instance(cls):
if cls._instance is None:
cls._instance = cls(...)
return cls._instance
使用类方法获取实例而不是构造函数的地方。Python的元编程允许更好的方法,例如Wikipedia上的方法:
class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls, *args, **kw):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
class MyClass(object):
__metaclass__ = Singleton
print MyClass()
print MyClass()
添加回答
举报