单例模式
单例模式(singletion pattern)
它是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实力存在。当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场。
在python 中,可以用多种方法来实现单例模式
1 使用模块
2 使用__new__
3 使用装饰器(decorator)
4 使用元类(metaclass)
使用模块,python的模块就时天然的单例模式,在第一次导入时,会生成pyc文件,当第二次导入时,就会直接加载pyc文件,而不会执行模块代码。
上个例子说明
import threading class HandlerFactory: _instance = None _lock = threading.RLock() def __init__(self): if None != HandlerFactory._instance: raise Exception('This is a Singleton! use CMHandlerFactory.get_handler method') self.handler_map = {} @staticmethod def get_instance(): if None == HandlerFactory._instance: HandlerFactory._lock.acquire() if None == HandlerFactory._instance: HandlerFactory._instance = HandlerFactory() HandlerFactory._lock.release() return HandlerFactory._instance
上面的例子是比较安全的,适用于多线程。
事事有回音
凡事有交代
件件有着落

浙公网安备 33010602011771号