单例模式

单例模式(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
View Code

上面的例子是比较安全的,适用于多线程。

posted @ 2018-03-01 18:17  会开车的好厨师  阅读(45)  评论(0)    收藏  举报