Skip to content

Instantly share code, notes, and snippets.

@shiracamus
Last active February 26, 2024 05:52
Show Gist options
  • Save shiracamus/9b40a7a60594c3f7a97b1c3a7250fcb0 to your computer and use it in GitHub Desktop.
Save shiracamus/9b40a7a60594c3f7a97b1c3a7250fcb0 to your computer and use it in GitHub Desktop.
public class ParkingSimulator {
public static void main(String[] args) {
Parking parking = new Parking("駅前駐車場", 2);
Car car1 = new Car("品川33 あ 1234");
Car car2 = new Car("横浜555 い 5678");
Car car3 = new Car("多摩345 う 9012");
car1.park(parking);
car2.park(parking);
car3.park(parking);
car1.exit();
car3.park(parking);
car1.exit();
car2.park(parking);
}
}
interface Vehicle {
}
class Parking {
public final String name;
private ParkingSpace[] spaces;
Parking(String name, int capacity) {
this.name = name;
spaces = new ParkingSpace[capacity];
for (int i = 0; i < capacity; i++) {
spaces[i] = new ParkingSpace(i + 1);
}
}
public ParkingSpace searchAvailableSpace() {
for (var space: spaces) {
if (space.isAvailable()) {
return space;
}
}
return null;
}
}
class ParkingSpace {
public final int number;
private Vehicle vehicle;
ParkingSpace(int number) {
this.number = number;
}
boolean isAvailable() {
return vehicle == null;
}
void park(Vehicle vehicle) throws IllegalStateException {
if (!isAvailable()) {
throw new IllegalStateException("not available");
}
this.vehicle = vehicle;
}
void exit(Vehicle vehicle) throws IllegalStateException {
if (this.vehicle != vehicle) {
throw new IllegalStateException("not park");
}
this.vehicle = null;
}
}
class Car implements Vehicle
{
public final String number;
private ParkingSpace parkingSpace;
public Car(final String number)
{
this.number = number;
}
void park(Parking parking) {
if (parkingSpace != null) {
System.out.println("「" + number + "」は既に駐車しています");
return;
}
parkingSpace = parking.searchAvailableSpace();
if (parkingSpace == null) {
System.out.println("「" + number + "」は満車で停められませんでした");
return;
}
parkingSpace.park(this);
System.out.println("「" + number + "」は駐車番号" + parkingSpace.number + "に停めました");
}
void exit() {
if (parkingSpace == null) {
System.out.println("「" + number + "」は駐車していません");
return;
}
parkingSpace.exit(this);
parkingSpace = null;
System.out.println("「" + number + "」は出庫しました");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment