Singleton implementation using metaclass
这里是一段Python代码,展示了如何利用metaclass来实现一个通用的Singleton,这使任何一个class都可以简单的复用这一行为:
这是一个简单的meta programming的应用展示,展示了metaclass所蕴涵的强大的能力,只要想得到,metaclass可以实现各种各样用通常手法做不到或很难实现的功能。:D
class Singleton(type):
def __call__(cls, *args):
if not hasattr(cls, 'instance'):
cls.instance = super(Singleton, cls).__call__(*args)
return cls.instance
class Cache(object):
__metaclass__ = Singleton
def main():
cache = Cache()
cache.data1 = 1
print 'data1 == %s' % cache.data1
cache2 = Cache()
cache2.data1 = cache2.data1 + 1
print 'data1 is increased by 1.'
print 'data1 == %s' % cache.data1
if __name__ == '__main__':
main()
def __call__(cls, *args):
if not hasattr(cls, 'instance'):
cls.instance = super(Singleton, cls).__call__(*args)
return cls.instance
class Cache(object):
__metaclass__ = Singleton
def main():
cache = Cache()
cache.data1 = 1
print 'data1 == %s' % cache.data1
cache2 = Cache()
cache2.data1 = cache2.data1 + 1
print 'data1 is increased by 1.'
print 'data1 == %s' % cache.data1
if __name__ == '__main__':
main()
这是一个简单的meta programming的应用展示,展示了metaclass所蕴涵的强大的能力,只要想得到,metaclass可以实现各种各样用通常手法做不到或很难实现的功能。:D