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