Elevator bank
Four elevators, twenty floors. External buttons call an elevator with a direction; internal buttons choose a destination. The dispatch algorithm needs to be swappable.
Assign each responsibility to its owner.
- Decide which car answers a hall call
- Dispatcher
- Track current floor and direction of travel
- ElevatorCar
- Hold origin floor, direction and timestamp
- Request
- Keep an ordered set of stops for one car
- ElevatorCar
- Enforce the obstruction sensor and hold time
- DoorController
A car knows only about itself: where it is, where it is going next. The Dispatcher is the only component with a global view, which is what makes it the only place a scheduling policy can live. Splitting door timing out keeps the car from accumulating unrelated state machines.
A car behaves differently when Idle, Moving, and DoorsOpen — and some commands are illegal in some modes. Best structure?
- Boolean flags isMoving and isDoorOpen
- A State pattern where each state class permits only its legal transitions
- A switch on an enum inside every method
- Separate classes MovingElevator and IdleElevator by inheritance
State. Illegal transitions become structurally impossible instead of being guarded by conditionals repeated in every method. Boolean flags produce combinations that should never exist — isMoving && isDoorOpen — and eventually one of them occurs.
Why is "send the physically closest car" a poor dispatch policy on its own?
- It is expensive to compute
- A closer car may be travelling the opposite direction, or already full
- It requires a database
- It cannot be unit tested
Distance alone ignores direction and load. A car two floors away heading down is worse than one five floors away already heading up. Real schedulers score candidates on direction agreement, existing stop list and load, which is precisely why the policy must be a swappable strategy.