Coursify

Mastering Low Level Design (LLD)

Designing an Elevator System

30 mins

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

  1. Multiple Elevators: A bank of elevators working together.
  2. Requests:
    • Internal: A passenger inside chooses a floor.
    • External: A passenger on a floor presses Up or Down.
  3. States: Idle, Moving Up, Moving Down, Doors Open, Maintenance.
  4. 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

  1. 1
    Step 1

    A user on Floor 5 presses 'UP'. The ExternalRequest (Floor: 5, Direction: UP) is sent to the ElevatorController.

  2. 2
    Step 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.

  3. 3
    Step 3

    The selected elevator adds Floor 5 to its upQueue. It uses a Min-Heap for upQueue and a Max-Heap for downQueue to always process the nearest floor first.

  4. 4
    Step 4

    If the elevator was Idle, it transitions to MovingUp. As it passes floors, it checks its queue. At Floor 5, it stops, opens doors, and removes the floor from the queue.

Knowledge Check

Question 1 of 3
Q1Single choice

Which design pattern is most effective for managing the different operational modes (Idle, Moving, DoorsOpen) of an elevator?