java - 如何在运行模拟中获取对象的实例?
问题描述
我正在编写一个小程序来控制地下车库。
该程序作为一个小型模拟运行,我想在运行时访问某些变量的状态变化等。
但我不确切知道如何实现它。
地下停车场类:
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 实例?谁能告诉我如何最好地进行?
解决方案
推荐阅读
- flutter - Dart/Flutter super(key:key) 示例
- html - 用于 SVG 的 IOS 间距
- algorithm - 匹配爱好时应该使用什么算法?
- python - 使用apply函数时如何修复类型错误
- function - 具有多个默认参数的 Kotlin 函数:如何忽略值?
- elasticsearch - AWS ElasticSearch 域创建权限
- kubernetes - 检索服务端口作为部署的模板变量
- scala - Scala/Chisel 中的函数式 for 循环
- mongodb - 从 mongo 获取具有持续时间的数据
- excel - 单击保存按钮后如何在用户窗体中添加依赖于另一个组合框的excel vba组合框而不影响清除数据功能