ctci/07. Object-Oriented design/7.4. Parking lot.md

1.7 KiB

7.4. Parking lot

Design a parking lot using object-oriented principles

public class ParkingLot {
    private final int NUMSPOTS = 1000;
    private final int NORMALHFEE = 0.25;
    private final Time OPENINGH = new Time(800);
    private final Time CLOSINGH = new Time(2000);
    protected ArrayList<Car> allCars = new ArrayList<Car>();
    private int carsInParking = 0;

    public int hiCar(Time comingtime) {
        if (carsInParking < NUMSPOTS) {
            if (comingtime < OPENINGH || comingtime > CLOSINGH) {
                allCars.push(new Car(comingtime));
                carsInParking++;
            }
            return 1;
        }
        return null;
    }

    /*
    The car can only be retrieved during 8:00 and 20:00, but many days later.
    */
    private int calculateCost(Car myCar) {
        return (myCar.DEPARTUREH - myCar.ARRIVALH) * NORMALHFEE;
    }

    public int byeCar(Car myCar, Time goingtime) {
        if (carsInParking < 0) {
            return -1;
        }
        if (!allCars.contains(myCar)) {
            return -1;
        }
        if (goingtime < myCar.ARRIVALH) {
            return -1;
        }
        myCar.setDepTime(goingtime);
        allCars.pop(myCar);
        carsInParking--;
        Car.setCost(calculateCost(myCar));
        return 1;
    }
}

public class Car {
    private Time ARRIVALH = null;
    private Time DEPARTUREH = null;
    private int cost;

    protected Car(Time arrivaltime) {
        ARRIVALH = arrivaltime;
    }

    public void setDepTime(Time goingtime) {
        DEPARTUREH = goingtime;
    }

    public void setCost(int parkingcost) {
        cost = parkingcost;
    }
}

Solution

Think about types of vehicles, and spots for these vehicles.