python单例模式的实现

时间:2021-08-20 07:47:04

1 线程不安全的单例模式

 # -*- coding:utf-8 -*-
from __future__ import unicode_literals import functools def singleton(func):
"""线程不安全的单例模式""" @functools.wraps(func)
def wrapper(*args, **kw):
if not hasattr(func, 'singleton_attr'):
func.singleton_attr = func(*args, **kw)
return func.singleton_attr return wrapper if __name__ == '__main__':
@singleton
def get_demo_list():
return [1, 2, 3] list_1 = get_demo_list()
list_2 = get_demo_list()
assert id(list_1) == id(list_2)

2 线程安全的单例模式

 # -*- coding:utf-8 -*-
from __future__ import unicode_literals import threading class SingletonMixin(object):
"""
thread safe singleton base class
refer: https://gist.github.com/werediver/4396488 # Based on tornado.ioloop.IOLoop.instance() approach.
# See https://github.com/facebook/tornado
"""
__singleton_lock = threading.Lock()
__singleton_instance = None @classmethod
def instance(cls):
""" :rtype: SingletonMixin
"""
if not cls.__singleton_instance:
with cls.__singleton_lock:
if not cls.__singleton_instance:
cls.__singleton_instance = cls()
return cls.__singleton_instance class SingleDemo(SingletonMixin):
def __init__(self):
pass @classmethod
def instance(cls):
""" :rtype: SingleDemo
"""
return super(SingleDemo, cls).instance() if __name__ == '__main__':
obj_1 = SingleDemo.instance()
obj_2 = SingleDemo.instance() assert id(obj_1) == id(obj_2)