Java实现conRoShipList内ConRoShip绑定专属BasicContainer子对象
实现方案
要完成船和容器的挂载关联,首先理清对象从属关系,避免结构混乱:
- ConRoShip实例自身要持有「自己搭载的所有容器」的引用,原代码将全局存储船实例的
conRoShipList定义在ConRoShip类内部,属于结构设计问题,这个列表是业务层统一维护的集合,不属于单艘船的属性 - 全局
conRoShipList仅负责存储所有已实例化的ConRoShip对象,遍历这个列表时,为每艘船的自有容器列表批量添加BasicContainer实例,即可完成对象关联
分步代码调整
1. 重构ConRoShip类,新增容器挂载的核心字段
在类内部新增专属的容器存储列表,同时封装挂载方法,结合已有的载重上限做超装校验,从根源上避免逻辑错误:
public class ConRoShip extends Ship { private final float MAX_SHIP_WEIGHT_CAPACITY = 15000.00f; private float initialShipCapacity = 2000.00f; // 新增:记录当前已装载的总重量,配合上限做校验 private float currentLoadedWeight = 0.0f; // 核心关联字段:单艘船自身挂载的容器列表 private final List<BasicContainer> mountedContainers = new LinkedList<>(); public ConRoShip(String name, String homePort, String transportSourceLocation, String transportDestination) { super(name, homePort, transportSourceLocation, transportDestination); shipCapacity += initialShipCapacity; } /** * 挂载容器到当前船只,自动做载重校验 * @param container 待挂载的BasicContainer实例 * @return 挂载成功返回true,超装返回false */ public boolean mountContainer(BasicContainer container) { // 校验总毛重是否超过船只最大载重 if (currentLoadedWeight + (float) container.getGrossWeight() > MAX_SHIP_WEIGHT_CAPACITY) { return false; } mountedContainers.add(container); currentLoadedWeight += (float) container.getGrossWeight(); return true; } // 对外提供只读的已挂载容器列表,避免外部随意修改内部结构 public List<BasicContainer> getMountedContainers() { return Collections.unmodifiableList(mountedContainers); } }
说明:
getGrossWeight()是BasicContainer父类Container已有的方法,可直接获取容器毛重做载重判断。
2. 调整全局船列表的归属
把原代码中错误嵌套在ConRoShip类内部的conRoShipList移到业务层统一维护:
// 业务层维护的全局ConRoShip实例列表,和需求场景完全匹配 List<ConRoShip> conRoShipList = new LinkedList<ConRoShip>(); // 示例:向列表存入已实例化的船对象 conRoShipList.add(new ConRoShip("远洋1号", "上海港", "上海", "洛杉矶")); conRoShipList.add(new ConRoShip("远洋2号", "深圳港", "深圳", "汉堡"));
3. 批量为每艘船挂载5个BasicContainer
直接遍历全局船列表,为每艘船循环生成BasicContainer实例,调用封装好的挂载方法完成关联:
// 遍历列表内所有已实例化的ConRoShip for (ConRoShip ship : conRoShipList) { // 单艘船循环挂载5个BasicContainer for (int mountIndex = 0; mountIndex < 5; mountIndex++) { // 按业务参数构造BasicContainer实例,替换成实际业务值即可 BasicContainer container = new BasicContainer( "集装箱-" + mountIndex, "合作发货方", "普通货运安全等级", 2.5, 2.8, 1000 ); ship.mountContainer(container); } }
效果说明
执行完上述逻辑后,每个ConRoShip对象内部会独立维护自己的关联容器列表,不会出现跨船的引用混乱。后续需要查询某艘船的搭载容器时,直接调用getMountedContainers()即可获取对应的BasicContainer集合。
内容的提问来源于stack exchange,提问作者matrix1395
相关产品推荐
相关产品推荐

