创建型模式-单例模式(使用装饰器实现)

# 创建型模式-单例模式(使用装饰器实现)
# 线程锁:防止创建多个实例
# 双重检查:实例创建后,防止重复加锁占用资源

from threading import Lock
from concurrent.futures import ThreadPoolExecutor

def single_decorator(cls):
    _lock = Lock()
    _instince = {}

    def wrapper(*args, **kwargs):
        if cls not in _instince:
            with _lock:
                if cls not in _instince:
                    import time
                    time.sleep(1)
                    _instince[cls] = cls(*args, **kwargs)
        return _instince[cls]
    return wrapper


@single_decorator
class Test():
    pass


def get_instance():
    b = Test()
    print(id(b))


if __name__ == "__main__":
    poll = ThreadPoolExecutor(max_workers=5)
    for i in range(10):
        poll.submit(get_instance)

  



posted @ 2023-06-27 13:46  你看起来真的很好吃  阅读(9)  评论(0编辑  收藏  举报