Singleton作为一种常用的设计模式。以下是Python版的几种实现方式:
1 class SingleDecorator(object):
def __init__(self, cls):
self.cls = cls
self._inst = None
def __call__(self, *args, **kwargs):
if not self._inst:
self._inst = self.cls(*args, **kwargs)
return self._inst
#for use
Example=SingleDecorator(Example)
a=Example()
b=Exampe()