前两天一个面试被问到python中单例模式有几种实现方式,只答出了可以用元类实现。。。然后就想不起来了。
之后翻书,原来这些之前都见过的啊。。。。
1.手动实现真正创建实例的方法__new__()来实现
class Singleton(object):
_instance = None def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance if __name__ == '__main__':
s1 = Singleton()
s2 = Singleton()
assert id(s1) == id(s2)
2,利用元类实现:
class Singleton(type):
def __init__(cls, name, bases, dic):
super(Singleton, cls).__init__(name, bases, dic)
cls.instance = None def __call__(cls, *args, **kwargs):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kwargs)
return cls.instance class MySingleton(object):
__metaclass__ = Singleton
3,利用装饰器实现
def Singleton1(aclass):
instance = None
def oncall(*args):
nonlocal instance
if instance == None
instance = aclass(*args)
return instance
return oncall class singleton2:
def __init__(self, aclass):
self.aclass = aclass
self.instance = None def __call__(self, *args):
if self.instance == None:
self.instance = self.aclass(*args)
return self.instance
4.共享属性
class Borg(object):
_state = {}
def __new__(cls, *args, **kw):
ob = super(Borg, cls).__new__(cls, *args, **kw)
ob.__dict__ = cls._state
return ob class MyClass2(Borg):
a = 1
5.import实现
# mysingleton.py
class My_Singleton(object):
def foo(self):
pass my_singleton = My_Singleton() # to use
from mysingleton import my_singleton my_singleton.foo()
参考资料:1.改善python程序的91个建议
2.Python学习手册
3.http://python.jobbole.com/85231/
4.Python Cookbook