You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java地下车库模拟运行时如何获取UndergroundCarPark实例

地下车库模拟实例访问解决方案

问题核心原因

  • 你设计的UndergroundCarPark采用单例模式,但未将构造方法私有化,导致外部可以直接调用new创建新实例,绕过了单例控制逻辑
  • UndergroundCarParkSimulation的构造方法中直接使用new UndergroundCarPark()创建实例,没有调用getInstance()方法,导致模拟类里的实例没有赋值给静态的singleton变量,后续调用getInstance()就会生成新的空实例

最优实现方案

方案1:保留单例模式(全局仅存在一个车库实例场景)

第一步:私有化UndergroundCarPark构造方法,强制所有实例获取走getInstance()

public class UndergroundCarPark {
    private static UndergroundCarPark singleton = null;

    List<Floor> etagen = new ArrayList<>();
    int numberOfFloors = 0;
    int numberOfParkingSpaces = 0;

    // 私有构造,禁止外部直接new创建实例
    private UndergroundCarPark() {}

    public static UndergroundCarPark getInstance() {
        if (singleton == null) {
            singleton = new UndergroundCarPark();
        }
        return singleton;
    }

    public void initUndergroundCarPark(int numberOfFloors, int numberOfParkingSpaces) {
        // 新增重复初始化判断,避免多次调用出错
        if (this.etagen.size() > 0) {
            return;
        }
        this.numberOfFloors = numberOfFloors;
        this.numberOfParkingSpaces = numberOfParkingSpaces;

        for (int i = 0; i < numberOfFloors; i++) {
            etagen.add(new Floor((numberOfParkingSpaces / numberOfFloors), i));
        }
    }

    // 其余方法省略
}

第二步:修改UndergroundCarParkSimulation构造方法,改用getInstance()获取单例

public class UndergroundCarParkSimulation {
    UndergroundCarPark undergroundCarPark;

    public UndergroundCarParkSimulation(int numberOfFloors, int numberOfParkingSpaces) {
        // 走单例接口获取实例,保证全局唯一
        undergroundCarPark = UndergroundCarPark.getInstance();
        undergroundCarPark.initUndergroundCarPark(numberOfFloors, numberOfParkingSpaces);
    }

    // 其余方法省略
}

修改后Main方法无需调整,调用UndergroundCarPark.getInstance()拿到的就是模拟类中已经完成初始化的同一实例,可直接访问状态变量。


方案2:放弃单例模式(支持多模拟实例并行场景)

如果后续需要同时运行多个独立的车库模拟,更推荐该方案,耦合度更低:

第一步:给UndergroundCarParkSimulation新增实例获取方法

public class UndergroundCarParkSimulation {
    UndergroundCarPark undergroundCarPark;

    public UndergroundCarParkSimulation(int numberOfFloors, int numberOfParkingSpaces) {
        undergroundCarPark = new UndergroundCarPark();
        undergroundCarPark.initUndergroundCarPark(numberOfFloors, numberOfParkingSpaces);
    }

    // 新增getter方法返回内部车库实例
    public UndergroundCarPark getUndergroundCarPark() {
        return this.undergroundCarPark;
    }

    // 其余方法省略
}

第二步:修改Main方法持有模拟类引用,通过getter获取实例

public static void main(String[] args) {
    // 持有模拟类实例引用
    UndergroundCarParkSimulation simulation = new UndergroundCarParkSimulation(4, 80);
    // 从模拟类中直接获取初始化完成的车库实例
    UndergroundCarPark undergroundCarPark = simulation.getUndergroundCarPark();

    // 模拟运行时访问状态变更
}

内容的提问来源于stack exchange,提问作者Hubi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 04:51:00