Designing an Elevator System
Master the design of an Elevator system, focusing on state management, concurrency, and dispatch algorithms.
Learning Goals
- Apply the State pattern to manage complex object behaviors.
- Design an efficient Dispatcher to handle multiple elevator requests.
- Visualize object state transitions using State Machine diagrams.
Case Study 2: The Elevator System
The Elevator system is a classic LLD problem because it involves complex state transitions and requires an efficient algorithm to minimize wait times. It is a perfect scenario for applying the State Pattern.
Step 1: Requirements
- Multiple Elevators: A bank of elevators working together.
- Requests:
- Internal: A passenger inside chooses a floor.
- External: A passenger on a floor presses Up or Down.
- States: Idle, Moving Up, Moving Down, Doors Open, Maintenance.
- Direction: An elevator must finish its current direction before reversing (Scan algorithm).
Step 2: The State Pattern
Managing multiple nested if-else statements for states like if(direction == UP && door == CLOSED && requestedFloor > currentFloor) is error-prone. Instead, we encapsulate each state into its own class.
Visualizing State Transitions
Logic: Dispatching an Elevator
- 1Step 1
A user on Floor 5 presses 'UP'. The
ExternalRequest(Floor: 5, Direction: UP) is sent to theElevatorController. - 2Step 2
The controller evaluates all elevators. It looks for an elevator that is: 1) Idle, 2) Moving towards the floor in the same direction, or 3) Nearest with the least workload.
- 3Step 3
The selected elevator adds Floor 5 to its
upQueue. It uses a Min-Heap forupQueueand a Max-Heap fordownQueueto always process the nearest floor first. - 4Step 4
If the elevator was
Idle, it transitions toMovingUp. As it passes floors, it checks its queue. At Floor 5, it stops, opens doors, and removes the floor from the queue.
Knowledge Check
Which design pattern is most effective for managing the different operational modes (Idle, Moving, DoorsOpen) of an elevator?