方法一:
- class Singleton(object):
- __instance = None
- def __init__():
- '''
- disable __init__
- '''
- pass
- def initInstance(self):
- pass
- @staticmethod
- def getInstance():
- '''
- this is the only access to get the instance of this class
- '''
- if(Singleton.__instance == None):
- Singleton.__instance = object.__new__(Singleton)
- Singleton.__instance.initInstance()
- return Singleton.__instance
- @staticmethod
- def destroyInstance():
- if(Singleton.__instance):
- Singleton.__instance = None
- if(__name__ == '__main__'):
- _singleton = Singleton.getInstance()
- _singleton.value = 'abc'
- print _singleton.value
- Singleton.destroyInstance()
方法二:
还可以在创建对象时利用__new__方法判断本类是否有对象存在,如果存在就返回已经存在的对象,如果不存在就创建新的对象并返回。可以直接在一个基类中记录类和生成的对象:
- class Singleton(object):
- __instances = {}
- def __new__(cls, *args, **kwargs):
- name = '.'.join((cls.__module__, cls.__name__))
- if name not in Singleton.__instances:
- Singleton.__instances[name] = object.__new__(cls, *args, **kwargs)
- return Singleton.__instances[name]
- if __name__ == "__main__":
- class T(Singleton):
- pass
- print T() is T()
方法三:
和方法二相似,但不记录类的对象,利用gc垃圾回收机制的引用来查找对象
- import gc
- class Singleton(object):
- def __new__(cls, *args, **kwargs):
- for obj in gc.get_referrers(cls):
- if obj.__class__ == cls:
- return obj
- return object.__new__(cls, *args, **kwargs)
- if __name__ == "__main__":
- class T(Singleton):
- pass
- print T() is T()
阅读(552) | 评论(0) | 转发(0) |