实现单例模式(python)
目录
方法一:重写__new__
xxxxxxxxxxclass Singleton(object): def __new__(cls, *args, **wargs): if not hasattr(cls, "_instance"): cls._instance = super(Singleton, cls).__new__(cls, *args, **wargs) return cls._instance
方法二:使用装饰器
xxxxxxxxxxdef decorate(cls): _instances = {} def _getInstance(*args, **kwargs): if cls not in _instances: _instances[cls] = cls(*args, **kwargs) return _instances[cls] return _getInstanceclass Singleton(object): pass
方法三:使用元类
x
class SingletonMeta(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(SingletonMeta, cls).__call__(*args, **kwargs) return cls._instances[cls]# for python3class Singleton(metaclass=SingletonMeta): pass# for python2class Singleton(object): __metaclass__ = SingletonMeta想要了解元类更多内容,请前往Python元类(metaclass)及其用途