Python装饰器单例

import threading
import time

def singleton(cls):
    instances = {}
    def get_instance(*args, **kwargs):
        # 判断实例是否已经存在
        if cls not in instances:
            # 如果不存在,创建新的实例并添加到字典中
            instances[cls] = cls(*args, **kwargs)
        # 返回该实例
        return instances[cls]
    # 返回内部函数get_instance
    return get_instance


@singleton
class UiData(object):
    selectedPc = None  # 单选按钮选中的pc
    show_selectedPc = None  # 单选按钮选中的pc

    capList = []

    # 运行状态码
    # 0代表未创建线程启动,1 启动 代表运行,2代表暂停,3代表结束
    pc1_run_state_code = 0
    pc2_run_state_code = 0
    pc3_run_state_code = 0
    pc4_run_state_code = 0
    pc5_run_state_code = 0
    pc6_run_state_code = 0
    pc7_run_state_code = 0
    pc8_run_state_code = 0
    pc9_run_state_code = 0
    pc10_run_state_code = 0
    pc11_run_state_code = 0
    pc12_run_state_code = 0

    # 刷图线程字典
    batting_thread_dict = {
        'pc1': None,
        'pc2': None,
        'pc3': None,
        'pc4': None,
        'pc5': None,
        'pc6': None,
        'pc7': None,
        'pc8': None,
        'pc9': None,
        'pc10': None,
        'pc11': None,
        'pc12': None
    }

    # 摄像头画面
    pc1_frame = None
    pc2_frame = None
    pc3_frame = None
    pc4_frame = None
    pc5_frame = None
    pc6_frame = None
    pc7_frame = None
    pc8_frame = None
    pc9_frame = None
    pc10_frame = None
    pc11_frame = None
    pc12_frame = None

    # 摄像头线程锁
    pc_frame_locks_dict = {
        'pc1': threading.Lock(),
        'pc2': threading.Lock(),
        'pc3': threading.Lock(),
        'pc4': threading.Lock(),
        'pc5': threading.Lock(),
        'pc6': threading.Lock(),
        'pc7': threading.Lock(),
        'pc8': threading.Lock(),
        'pc9': threading.Lock(),
        'pc10': threading.Lock(),
        'pc11': threading.Lock(),
        'pc12': threading.Lock()
    }

    @classmethod
    def getFrame(cls, pc):
        pc_frame_dict = {
            "pc1": cls.pc1_frame,
            "pc2": cls.pc2_frame,
            "pc3": cls.pc3_frame,
            "pc4": cls.pc4_frame,
            "pc5": cls.pc5_frame,
            "pc6": cls.pc6_frame,
            "pc7": cls.pc7_frame,
            "pc8": cls.pc8_frame,
            "pc9": cls.pc9_frame,
            "pc10": cls.pc10_frame,
            "pc11": cls.pc11_frame,
            "pc12": cls.pc12_frame
        }

        frame = pc_frame_dict.get(pc)
        return frame




class CenterData:
    UiData = UiData


if __name__ == '__main__':
    # 创建UiData的实例
    uidata1 = UiData()
    uidata2 = UiData()
    # 单例 id相同
    print(id(uidata1))
    print(id(uidata2))

 

posted @ 2023-11-28 20:13  zwnsyw  阅读(22)  评论(0编辑  收藏  举报