Python使用metaclass实现Singleton模式的方法
本文实例讲述了Python使用metaclass实现Singleton模式的方法。分享给大家供大家参考。具体实现方法如下:
classSingleton(type): def__call__(cls,*args,**kwargs): print"Singletoncall" ifnothasattr(cls,'instance'): cls.instance=super(Singleton,cls).__call__(*args,**kwargs) returncls.instance def__new__(cls,name,bases,dct): print"Singletonnew" returntype.__new__(cls,name,bases,dct) def__init__(cls,name,bases,dct): print"Singletoninit" super(Singleton,cls).__init__(name,bases,dct) classCache(object): __metaclass__=Singleton def__new__(cls,*args,**kwargs): print"Cachenew" returnobject.__new__(cls,*args,**kwargs) def__init__(cls,*args,**kwargs): print"Cacheinit" def__call__(cls,*args,**kwargs): print"Cachecall" printCache() printCache()
输出:
Singletonnew Singletoninit Singletoncall Cachenew Cacheinit <__main__.Cacheobjectat0x01CDB130> Singletoncall <__main__.Cacheobjectat0x01CDB130>
希望本文所述对大家的Python程序设计有所帮助。