如果你想在Python中创建一个可以从任何地方访问的唯一“对象”,只需创建一个仅包含静态属性、@staticmethod和@classmethod的类Unique
,你可以将其称为唯一模式。 这里我实现并比较了3种模式:
唯一模式
class Unique:
x = 1
@classmethod
def init(cls):
return cls
单例模式
class Singleton:
__single = None
def __init__(self):
if not Singleton.__single:
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
class Borg:
__monostate = None
def __init__(self):
if not Borg.__monostate:
Borg.__monostate = self.__dict__
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))
输出:
SINGLETON(单例模式)
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模式,但它需要定义两个函数,显得有些丑陋。