实现单例模式(python)
目录
方法一:重写__new__
xxxxxxxxxx
class Singleton(object):
def __new__(cls, *args, **wargs):
if not hasattr(cls, "_instance"):
cls._instance = super(Singleton, cls).__new__(cls, *args, **wargs)
return cls._instance
方法二:使用装饰器
xxxxxxxxxx
def decorate(cls):
_instances = {}
def _getInstance(*args, **kwargs):
if cls not in _instances:
_instances[cls] = cls(*args, **kwargs)
return _instances[cls]
return _getInstance
class 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 python3
class Singleton(metaclass=SingletonMeta):
pass
# for python2
class Singleton(object):
__metaclass__ = SingletonMeta
想要了解元类更多内容,请前往Python元类(metaclass)及其用途