首页 > 解决方案 > 如何在运行模拟中获取对象的实例?

问题描述

我正在编写一个小程序来控制地下车库。

该程序作为一个小型模拟运行,我想在运行时访问某些变量的状态变化等。

但我不确切知道如何实现它。

地下停车场类:

public class UndergroundCarPark {
private static UndergroundCarPark singleton = null;

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

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

public void initUndergroundCarPark(int numberOfFloors, int numberOfParkingSpaces) {
    this.numberOfFloors = numberOfFloors;
    this.numberOfParkingSpaces = numberOfParkingSpaces;

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

}

// some more methods...

类 UndergroundCarParkSimulation:

public class UndergroundCarParkSimulation {

UndergroundCarPark undergroundCarPark;

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

// some more methods
}

主要的:

    public static void main(String[] args) {

    new UndergroundCarParkSimulation(4, 80);

    UndergroundCarPark undergroundCarPark = UndergroundCarPark.getInstance();

    // access to state changes while simulation is running

}

我意识到如果我运行这条线,

UndergroundCarParkundergroundCarPark = UndergroundCarPark.getInstance();

我会得到一个新的 UndergroundCarPark 对象。因为 UndergroundCarPark 类的 getInstance 返回一个新对象。

如何访问在模拟类中创建的 UndergroundPark 实例?谁能告诉我如何最好地进行?

标签: javainstance

解决方案


推荐阅读