1

I am writing a small program to control an underground garage.

The program runs as a small simulation and I would like to have access to state changes of certain variables etc. while this is running.

But I don't know exactly how to implement it.

Class UndergroundCarPark:

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...

Class UndergroundCarParkSimulation:

public class UndergroundCarParkSimulation {

UndergroundCarPark undergroundCarPark;

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

// some more methods
}

Main:

    public static void main(String[] args) {

    new UndergroundCarParkSimulation(4, 80);

    UndergroundCarPark undergroundCarPark = UndergroundCarPark.getInstance();

    // access to state changes while simulation is running

}

I realize that if I run this line,

UndergroundCarPark undergroundCarPark = UndergroundCarPark.getInstance();

I will get a new UndergroundCarPark object. Because getInstance from the UndergroundCarPark Class returns a new Object.

How is it possible to access the instance of UndergroundPark which is created in the simulation class? Can anyone tell me how best to proceed?

Hubi
  • 440
  • 1
  • 11
  • 25
  • 1
    Look at the implementation of `getInstance`. It only creates a new object the first time it is called. On second and subsequent calls it returns the object it created on the first call. (It isn't thread-safe, so if your simulation uses multiple threads you would need to fix that). However `UndergroundCarParkSimulation` doesn't use `getInstance` for some reason, so it is creating its own instance. – tgdavies Sep 18 '21 at 07:45
  • Yeah right... hat to first call getInstance in UndergroundCarParkSimulation.. no it runs.. Thanks. – Hubi Sep 18 '21 at 08:33

0 Answers0