Java OOP项目中如何不使用switch case创建不同类型的组件对象
解决方案
你可以通过工厂映射表的方式彻底替换switch case逻辑,完全符合面向对象的开闭原则,后续新增组件也不需要修改核心创建逻辑,非常适配你的课程项目要求。
实现步骤
1. 定义静态构造函数映射表
你可以在GUI类或者单独的组件工具类中,定义一个Map存储组件名称和对应构造方法的引用,Java 8及以上版本可以直接用方法引用简化代码:
import java.util.HashMap; import java.util.Map; import java.util.function.Function; // 映射表:键是列表选中的组件名称,值是接收输入端口数、返回逻辑组件实例的构造函数 private static final Map<String, Function<Integer, ComponenteLogico>> COMPONENT_FACTORY = new HashMap<>(); // 类加载时注册所有支持的组件 static { COMPONENT_FACTORY.put("AND", portaAND::new); COMPONENT_FACTORY.put("OR", portaOR::new); COMPONENT_FACTORY.put("NAND", portaNAND::new); COMPONENT_FACTORY.put("NOR", portaNOR::new); // 后续新增组件只要在这里加一行注册即可,不用修改创建逻辑 }
2. 替换原有点击事件的switch逻辑
把你原有的if/switch代码替换为从映射表取构造函数直接创建实例的逻辑:
int inputs = jComboBox1.getSelectedIndex() + 2; ComponenteLogico comp = null; String selectedType = jList1.getSelectedValue(); if (selectedType == null) { System.out.println("未创建任何组件"); System.out.println("测试1"); } else { Function<Integer, ComponenteLogico> constructor = COMPONENT_FACTORY.get(selectedType); if (constructor != null) { comp = constructor.apply(inputs); } else { System.out.println("不支持的组件类型:" + selectedType); } }
可选方案:枚举封装创建逻辑
如果你的教授要求更规范的类型约束,可以用枚举类封装所有组件的创建行为:
public enum ComponentType { AND(portaAND::new), OR(portaOR::new), NAND(portaNAND::new), NOR(portaNOR::new); private final Function<Integer, ComponenteLogico> constructor; ComponentType(Function<Integer, ComponenteLogico> constructor) { this.constructor = constructor; } public ComponenteLogico newInstance(int inputs) { return constructor.apply(inputs); } }
使用时直接把选中的字符串转成枚举即可:
if (selectedType != null) { try { ComponentType type = ComponentType.valueOf(selectedType); comp = type.newInstance(inputs); } catch (IllegalArgumentException e) { System.out.println("不支持的组件类型"); } }
内容的提问来源于stack exchange,提问作者Lorenzo Mondo
相关产品推荐
相关产品推荐

