python 单例模式,综合了网上几种后,选的一种:
代码如下:
# 用户管理器
class UserManager(object):
# 定义静态变量实例
__instance = None
__lock = threading.Lock()
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if not cls.__instance:
try:
UserManager.__lock.acquire()
# double check
if not cls.__instance:
cls.__instance = super(UserManager, cls).__new__(cls, *args, **kwargs)
finally:
UserManager.__lock.release()
return cls.__instance
考虑了多线程的情况,使用时代码如下:
user_manager = UserManager()