我们用2种方式来实现singleton, 修饰类的方式和元类的方式:
修饰类的方式
class Singleton:
def __init__( self, decorated ):
self._decorated = decorated
def Instance( self ):
try:
return self._instance
except AttributeError:
self._instance = self._decorated
return self._instance
def __call__( self ):
raise TypeError( 'single instance allowed' )
@Singleton
class CA:
def __init__( self ):
print( 'created' )
要创建CA的实例,不能再用
a = CA()
的方式,这种方式会产生一个异常。
而是通过 Instance()这个方法:
a = CA.Instance()
b = CA.instance()
id(a)
id(b)
你就会发现id(a) 和id(b) 返回是同一个id
元类的方式
class Singleton(type):
def __init__(cls,name,bases,dic):
super(Singleton,cls).__init__(name,bases,dic)
cls.instance = None
def __call__(cls,*args,**kwargs):
if cls.instance is None:
cls.instance = super(Singleton,cls).__call__(*args,**kwargs)
return cls.instance
class MyClass(object):
__metaclass__ = Singleton
def __init__(self,arg):
self.arg = arg
测试如下:
my1 = MyClass("hello")
my2 = MyClass("world")
>>> my1 is my2
True