首页 > 其他 > 详细

使用装(修饰器)来实现单例模式

时间:2019-02-01 21:25:42      阅读:222      评论:0      收藏:0      [点我收藏+]
import threading


# 装饰器
def synchronized(func):
    func.__lock__ = threading.Lock()

    def synced_func(*args, **kws):
        with func.__lock__:
            return func(*args, **kws)

    return synced_func


# 使用修饰器来实现单例模式
def singleton(cls):
    instances = {}

    @synchronized
    def get_instance(*args, **kw):
        if cls not in instances:
            instances[cls] = cls(*args, **kw)
        return instances[cls]

    return get_instance


def worker():
    single_test = Test()
    print("id----> %s" % id(single_test))


@singleton
class Test(object):
    a = 1


if __name__ == "__main__":
    task_list = []
    for one in range(5):
        t = threading.Thread(target=worker)
        task_list.append(t)

    for one in task_list:
        one.start()

    for one in task_list:
        one.join()

使用装(修饰器)来实现单例模式

原文:https://www.cnblogs.com/apollo1616/p/10347052.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!