I got a question:
Design a parking system. There are 3 types of parking spaces: big, medium and small.
Implement ParkingSystem class(int big, int medium, int small)
. Constructor takes a number of places of types. So ParkingSystem(1,2,3)
means there are 1 big place, 2 medium and 3 small.
Add method addCar(int carType)
- carType takes one of three values [1,2,3] which represents big car, medium car and small car.
Method should check if there is a place for a car of such size or bigger, if yes then it parks the car in this place and returns true, else false.
For now there is no method to free parking space (when a car is leaving) but it can be added in future.
Example:
- ParkingSystem ps = new ParkingSystem(1, 2, 3); // creates parking with 1 big place, 2 medium and 3 small
- ps.addCar(2); //true, medium car takes medium place
- ps.addCar(2); //true, medium car takes medium place
- ps.addCar(2); //true, medium car takes big place
- ps.addCar(1); //false, no place for big car
I wrote:
public class ParkingSystem {
private int big;
private int medium;
private int small;
public ParkingSystem(int big, int medium, int small) {
this.big = big;
this.medium = medium;
this.small = small;
}
public boolean addCar(int car) {
if (car == 1 && isPlaceForBigCar()) {
return parkBigCar();
} else if (car == 2 && isPlaceForMediumCar()) {
return parkMediumCar();
} else if (car == 3 && isPlaceForSmallCar()) {
return parkSmallCar();
}
return false;
}
private boolean parkBigCar() {
this.big--;
return true;
}
private boolean parkMediumCar() {
if (medium > 0) {
this.medium--;
} else if (big > 0) {
this.big--;
}
return true;
}
private boolean parkSmallCar() {
if (small > 0) {
this.small--;
} else if (medium > 0) {
this.medium--;
} else if (big > 0) {
this.big--;
}
return true;
}
private boolean isPlaceForBigCar() {
return this.big > 0;
}
private boolean isPlaceForMediumCar() {
return (this.big > 0 || this.medium > 0);
}
private boolean isPlaceForSmallCar() {
return (this.big > 0 || this.medium > 0 || this.small > 0);
}
}
so it seems to be a little better than the worst solution but I believe there is still a lot to improve. Should I use strategy pattern to park cars or is there even better solution?
Main/Test class:
public class Main {
public static void main(String[] args) {
ParkingSystem ps = new ParkingSystem(1, 2, 3); // creates parking with 1 big place, 2 medium and 3 small
System.out.println(ps.addCar(2)); //true, medium car takes medium place
System.out.println(ps.addCar(2)); //true, medium car takes medium place
System.out.println(ps.addCar(2)); //true, medium car takes big place
System.out.println(ps.addCar(1)); //false, no place for big car
}
}
isPlaceForSmallCar
andparkSmallCar
methods. \$\endgroup\$