美文网首页
Python 单例模式(Singleton Pattern)

Python 单例模式(Singleton Pattern)

作者: 白鬓少年 | 来源:发表于2020-07-24 15:18 被阅读0次

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()

相关文章

网友评论

      本文标题:Python 单例模式(Singleton Pattern)

      本文链接:https://www.haomeiwen.com/subject/ubijlktx.html