package com.car.model; import java.util.ArrayList; import java.util.List; /** * 引擎类 - 汽车的核心组件 * 与Car类是组合关系,包含Piston组件的组合关系 */ public class Engine { private String type; // 引擎类型 private int horsepower; // 马力 private double displacement; // 排量 private List pistons; // 活塞列表 - 组合关系 /** * 构造方法 * @param type 引擎类型 * @param horsepower 马力 * @param displacement 排量 * @param pistonCount 活塞数量 */ public Engine(String type, int horsepower, double displacement, int pistonCount) { this.type = type; this.horsepower = horsepower; this.displacement = displacement; this.pistons = new ArrayList<>(pistonCount); // 初始化活塞 for (int i = 0; i < pistonCount; i++) { pistons.add(new Piston(85, 88, "Aluminum", 10)); } } // 添加活塞方法 public void addPiston(Piston piston) { pistons.add(piston); } // 替换活塞方法 public boolean replacePiston(int index, Piston newPiston) { if (index >= 0 && index < pistons.size()) { pistons.set(index, newPiston); return true; } return false; } // getter and setter methods public String getType() { return type; } public void setType(String type) { this.type = type; } public int getHorsepower() { return horsepower; } public void setHorsepower(int horsepower) { this.horsepower = horsepower; } public double getDisplacement() { return displacement; } public void setDisplacement(double displacement) { this.displacement = displacement; } public List getPistons() { return new ArrayList<>(pistons); // 返回副本,保持封装性 } @Override public String toString() { return "Engine [type=" + type + ", horsepower=" + horsepower + ", displacement=" + displacement + ", pistonsCount=" + pistons.size() + "]"; } }