python中单例的实现
单例的解释
单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。
import作为python的模块是天然的单例模式
可以使用模块创建单例模式,然后在其他模块中导入该单例,这个需要所有人遵守导入规则,不然就没法实现单例了
# use_module.py class SingleTon(object): def __init__(self, val): self.val = val single = SingleTon(2) # test_module.py from use_module import single a = single b = single print a.val, b.val print a is b a.val = 233 print a.val, b.val
使用__new__实现单例模式
class SingleTon(object): _instance = {} def __new__(cls, *args, **kwargs): if cls not in cls._instance: cls._instance[cls] = super(SingleTon, cls).__new__(cls, *args, **kwargs) # print cls._instance return cls._instance[cls] class MyClass(SingleTon): class_val = 22 def __init__(self, val): self.val = val def obj_fun(self): print self.val, 'obj_fun' @staticmethod def static_fun(): print 'staticmethod' @classmethod def class_fun(cls): print cls.class_val, 'classmethod' if __name__ == '__main__': a = MyClass(1) b = MyClass(2) print a is b # True print id(a), id(b) # 4367665424 4367665424 # 类型验证 print type(a) # <class '__main__.MyClass'> print type(b) # <class '__main__.MyClass'>
装饰器实现
from functools import wraps def single_ton(cls): _instance = {} @wraps(cls) def single(*args, **kwargs): if cls not in _instance: _instance[cls] = cls(*args, **kwargs) return _instance[cls] return single @single_ton class SingleTon(object): val = 123 def __init__(self, a): self.a = a if __name__ == '__main__': s = SingleTon(1) t = SingleTon(2) print s is t print s.a, t.a print s.val, t.val