package com.mes.interaction; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import javax.annotation.PostConstruct; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 设备逻辑处理器工厂类 * 根据设备类型获取对应的处理器 * * @author mes * @since 2025-01-XX */ @Slf4j @Component public class DeviceLogicHandlerFactory { @Autowired private List handlers; private final Map handlerMap = new HashMap<>(); /** * 初始化处理器映射 */ @PostConstruct public void init() { if (handlers != null) { for (DeviceLogicHandler handler : handlers) { String deviceType = handler.getDeviceType(); if (StringUtils.hasText(deviceType)) { String normalized = normalizeDeviceType(deviceType); handlerMap.put(normalized, handler); if (!normalized.equals(deviceType)) { handlerMap.put(deviceType, handler); } log.info("注册设备逻辑处理器: {} -> {}", deviceType, handler.getClass().getSimpleName()); } } } log.info("设备逻辑处理器初始化完成,共注册 {} 个处理器", handlerMap.size()); } /** * 根据设备类型获取对应的处理器 * * @param deviceType 设备类型 * @return 设备逻辑处理器,如果未找到返回null */ public DeviceLogicHandler getHandler(String deviceType) { if (!StringUtils.hasText(deviceType)) { return null; } DeviceLogicHandler handler = handlerMap.get(deviceType); if (handler != null) { return handler; } String normalized = normalizeDeviceType(deviceType); if (!normalized.equals(deviceType)) { handler = handlerMap.get(normalized); } return handler; } /** * 检查是否支持指定的设备类型 * * @param deviceType 设备类型 * @return true表示支持,false表示不支持 */ public boolean supports(String deviceType) { return deviceType != null && handlerMap.containsKey(deviceType); } /** * 获取所有已注册的设备类型 * * @return 设备类型集合 */ public java.util.Set getSupportedDeviceTypes() { return handlerMap.keySet(); } private String normalizeDeviceType(String deviceType) { if (!StringUtils.hasText(deviceType)) { return deviceType; } String trimmed = deviceType.trim(); if (trimmed.endsWith("设备")) { return trimmed.substring(0, trimmed.length() - 2); } return trimmed; } }