Python 单例模式(Singleton Pattern)

Singleton Pattern 是针对class的一种软件设计模式,用以确保该class在系统的生命周期内仅存在唯一一个实例。此文仅用于记录本人所常选用的一种单例模式,更多单例模式的实现方法参考一下连接:
werediver/singleton.py
Python单例模式
Python中的单例模式的几种实现方式的及优化
设计模式(Python)-单例模式

import time
import threading
class Singleton(object):
    _instance = None
    _instance_lock = threading.Lock()

    def __init__(self):
        pass

    @classmethod
    def instance(cls):
        with cls._instance_lock:
            if not cls._instance:
                cls._instance = cls()
        return cls._instance


def task(arg):
    obj = Singleton.instance()
    print(obj)
for i in range(10):
    t = threading.Thread(target=task,args=[i,])
    t.start()
time.sleep(20)
obj = Singleton.instance()
print(obj)

其中

with some_lock:
    # do something...

等同于

some_lock.acquire()
try:
    # do something...
finally:
    some_lock.release()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容