Java 接口设计实战:3种家电类实现与卡车总重计算(附完整代码)

📅 发布时间:2026/7/10 15:18:02 👁️ 浏览次数:
Java 接口设计实战:3种家电类实现与卡车总重计算(附完整代码)
Java接口设计实战家电管理系统与卡车载重计算在面向对象编程中接口是实现多态和代码解耦的重要工具。本文将通过一个完整的家电管理系统案例展示如何利用Java接口设计可扩展的应用程序架构。我们将从基础实现开始逐步深入到设计模式的应用最终构建一个支持轻松扩展新家电类型的系统。1. 系统需求分析与接口设计我们需要为家电企业开发一个卡车载重计算系统核心功能是统计每辆卡车装载的各种家电总重量。系统需要满足以下业务需求支持多种家电类型电视机、洗衣机、空调等每种家电都有自重属性卡车可以装载任意数量和组合的家电系统需要准确计算当前装载的总重量接口定义是系统设计的起点。我们创建一个Appliance接口它只包含一个获取重量的方法public interface Appliance { int getWeight(); }这个极简设计体现了接口的核心价值——定义行为契约而不关心具体实现。任何实现Appliance的类都必须提供getWeight()方法这保证了系统在处理各种家电时的一致性。2. 具体家电类实现基于上述接口我们实现三种具体的家电类。注意这些实现类除了重量属性外还可以包含各自特有的属性和方法。2.1 电视机类实现public class TV implements Appliance { private final int weight; private final String resolution; public TV(int weight, String resolution) { this.weight weight; this.resolution resolution; } Override public int getWeight() { return weight; } // 电视机特有方法 public String getResolution() { return resolution; } }2.2 洗衣机类实现public class WashMachine implements Appliance { private final int weight; private final int capacity; public WashMachine(int weight, int capacity) { this.weight weight; this.capacity capacity; } Override public int getWeight() { return weight; } // 洗衣机特有方法 public int getCapacity() { return capacity; } }2.3 空调类实现public class AirConditioner implements Appliance { private final int weight; private final String type; // 分体式、中央空调等 public AirConditioner(int weight, String type) { this.weight weight; this.type type; } Override public int getWeight() { return weight; } // 空调特有方法 public String getType() { return type; } }设计要点每个实现类都提供了getWeight()方法的具体实现实现类可以自由添加自己特有的属性和方法使用final关键字确保重量属性不可变构造方法强制初始化必要属性3. 卡车类与集合管理卡车类需要管理装载的家电集合并计算总重量。我们使用Java集合框架中的List来存储家电对象import java.util.ArrayList; import java.util.List; public class Truck { private final ListAppliance appliances; public Truck() { this.appliances new ArrayList(); } public void addAppliance(Appliance appliance) { appliances.add(appliance); } public int calculateTotalWeight() { return appliances.stream() .mapToInt(Appliance::getWeight) .sum(); } public int getApplianceCount() { return appliances.size(); } }关键设计决策设计选择优势考虑因素使用List集合动态扩展容量内存使用效率泛型Appliance类型安全编译时类型检查Stream API简洁的重量计算Java 8兼容性独立add方法灵活添加家电封装集合操作4. 系统扩展与维护接口设计的最大优势在于系统的可扩展性。当需要新增家电类型时只需实现Appliance接口即可无缝集成到现有系统中。4.1 添加新家电类型示例假设我们需要添加冰箱类public class Refrigerator implements Appliance { private final int weight; private final int volume; public Refrigerator(int weight, int volume) { this.weight weight; this.volume volume; } Override public int getWeight() { return weight; } public int getVolume() { return volume; } }4.2 工厂模式优化创建过程为了更好管理对象创建可以引入简单工厂模式public class ApplianceFactory { public static Appliance createAppliance(int type, int weight, Object... args) { switch(type) { case 1: return new TV(weight, (String)args[0]); case 2: return new WashMachine(weight, (Integer)args[0]); case 3: return new AirConditioner(weight, (String)args[0]); case 4: return new Refrigerator(weight, (Integer)args[0]); default: throw new IllegalArgumentException(未知家电类型); } } }4.3 主程序实现import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner new Scanner(System.in); Truck truck new Truck(); System.out.println(输入家电数量); int count scanner.nextInt(); for (int i 0; i count; i) { System.out.println(输入家电类型(1-TV,2-洗衣机,3-空调,4-冰箱)); int type scanner.nextInt(); System.out.println(输入家电重量); int weight scanner.nextInt(); Appliance appliance ApplianceFactory.createAppliance(type, weight, getAdditionalParams(scanner, type)); truck.addAppliance(appliance); } System.out.println(卡车装载总重量 truck.calculateTotalWeight()); scanner.close(); } private static Object[] getAdditionalParams(Scanner scanner, int type) { // 根据不同类型获取额外参数 // 实现略... } }5. 高级设计考量5.1 异常处理增强健壮性public class WeightCalculationException extends RuntimeException { public WeightCalculationException(String message) { super(message); } } // 在Truck类中 public int calculateTotalWeight() { if (appliances.isEmpty()) { throw new WeightCalculationException(卡车未装载任何家电); } return appliances.stream() .mapToInt(appliance - { int weight appliance.getWeight(); if (weight 0) { throw new WeightCalculationException(发现无效重量值 weight); } return weight; }) .sum(); }5.2 使用枚举强化类型安全public enum ApplianceType { TV(1), WASH_MACHINE(2), AIR_CONDITIONER(3), REFRIGERATOR(4); private final int code; ApplianceType(int code) { this.code code; } public int getCode() { return code; } public static ApplianceType fromCode(int code) { for (ApplianceType type : values()) { if (type.code code) { return type; } } throw new IllegalArgumentException(无效家电类型代码 code); } }5.3 日志记录与监控import java.util.logging.Logger; public class Truck { private static final Logger LOGGER Logger.getLogger(Truck.class.getName()); public void addAppliance(Appliance appliance) { appliances.add(appliance); LOGGER.info(添加家电 appliance.getClass().getSimpleName() 当前总数 appliances.size()); } public int calculateTotalWeight() { LOGGER.fine(开始计算卡车总重量); int total appliances.stream() .mapToInt(Appliance::getWeight) .sum(); LOGGER.info(卡车总重量计算完成 total); return total; } }在实际项目中接口设计只是起点。真正的系统还需要考虑持久化、网络通信、用户界面等更多方面。但良好的接口设计能够确保核心业务逻辑保持清晰和可维护为系统扩展奠定坚实基础。