python单例模式的实现
1 线程不安全的单例模式
1 # -*- coding:utf-8 -*- 2 from __future__ import unicode_literals 3 4 import functools 5 6 7 def singleton(func): 8 """线程不安全的单例模式""" 9 10 @functools.wraps(func) 11 def wrapper(*args, **kw): 12 if not hasattr(func, 'singleton_attr'): 13 func.singleton_attr = func(*args, **kw) 14 return func.singleton_attr 15 16 return wrapper 17 18 19 if __name__ == '__main__': 20 @singleton 21 def get_demo_list(): 22 return [1, 2, 3] 23 24 25 list_1 = get_demo_list() 26 list_2 = get_demo_list() 27 assert id(list_1) == id(list_2)
2 线程安全的单例模式
1 # -*- coding:utf-8 -*- 2 from __future__ import unicode_literals 3 4 import threading 5 6 7 class SingletonMixin(object): 8 """ 9 thread safe singleton base class 10 refer: https://gist.github.com/werediver/4396488 11 12 # Based on tornado.ioloop.IOLoop.instance() approach. 13 # See https://github.com/facebook/tornado 14 """ 15 __singleton_lock = threading.Lock() 16 __singleton_instance = None 17 18 @classmethod 19 def instance(cls): 20 """ 21 22 :rtype: SingletonMixin 23 """ 24 if not cls.__singleton_instance: 25 with cls.__singleton_lock: 26 if not cls.__singleton_instance: 27 cls.__singleton_instance = cls() 28 return cls.__singleton_instance 29 30 31 class SingleDemo(SingletonMixin): 32 def __init__(self): 33 pass 34 35 @classmethod 36 def instance(cls): 37 """ 38 39 :rtype: SingleDemo 40 """ 41 return super(SingleDemo, cls).instance() 42 43 44 if __name__ == '__main__': 45 obj_1 = SingleDemo.instance() 46 obj_2 = SingleDemo.instance() 47 48 assert id(obj_1) == id(obj_2)