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條經驗 獲得超5個贊
它不是。通常不建議在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()
添加回答
舉報