Skip to main content

Code Implementation

Editorial

Implementation Overview

We'll implement the Elevator System class by class, following our class diagram exactly. Every class in the diagram appears in the code, and every relationship is reflected in the implementation.

Implementation order:

  1. Enums — Direction, DoorStatus, ElevatorState, RequestType
  2. Request — the data model for floor requests
  3. Door — door mechanism with state management
  4. Scheduling Strategies — FCFS, SCAN, LOOK (implements SchedulingStrategy)
  5. Elevator — the core car with movement, stops, and request queue
  6. Floor Components — HallButton, FloorDisplay, ElevatorPanel
  7. Dispatcher — assigns hall calls to the optimal elevator
  8. ElevatorSystem — top-level orchestrator
  9. Usage Example — realistic multi-elevator scenario

Enums and Request Model

We start with enums for type safety — these define the fixed sets of values for direction, state, door status, and request type. The Request class models both hall calls and cabin calls with a unified interface.

from enum import Enum
from abc import ABC, abstractmethod
from typing import List, Optional, Dict, Set
import time


class Direction(Enum):
    UP = "UP"
    DOWN = "DOWN"
    IDLE = "IDLE"


class DoorStatus(Enum):
    CLOSED = "CLOSED"
    OPENING = "OPENING"
    OPEN = "OPEN"
    CLOSING = "CLOSING"


class ElevatorState(Enum):
    IDLE = "IDLE"
    MOVING_UP = "MOVING_UP"
    MOVING_DOWN = "MOVING_DOWN"
    DOOR_OPEN = "DOOR_OPEN"


class RequestType(Enum):
    HALL_CALL = "HALL_CALL"
    CABIN_CALL = "CABIN_CALL"


class Request:
    """Represents a floor request — either a hall call or cabin call."""

    def __init__(self, source_floor: int, destination_floor: int,
                 direction: Direction, request_type: RequestType):
        self.source_floor = source_floor
        self.destination_floor = destination_floor
        self.direction = direction
        self.request_type = request_type
        self.timestamp = time.time()

    def __repr__(self) -> str:
        return (f"Request(src={self.source_floor}, dest={self.destination_floor}, "
                f"dir={self.direction.value}, type={self.request_type.value})")

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Request):
            return False
        return (self.source_floor == other.source_floor and
                self.destination_floor == other.destination_floor and
                self.direction == other.direction)

    def __hash__(self) -> int:
        return hash((self.source_floor, self.destination_floor, self.direction))
import java.util.*;
import java.util.stream.Collectors;

// --- Enums ---

public enum Direction {
    UP, DOWN, IDLE
}

public enum DoorStatus {
    CLOSED, OPENING, OPEN, CLOSING
}

public enum ElevatorState {
    IDLE, MOVING_UP, MOVING_DOWN, DOOR_OPEN
}

public enum RequestType {
    HALL_CALL, CABIN_CALL
}

// --- Request ---

public class Request {
    private final int sourceFloor;
    private final int destinationFloor;
    private final Direction direction;
    private final RequestType requestType;
    private final long timestamp;

    public Request(int sourceFloor, int destinationFloor,
                   Direction direction, RequestType requestType) {
        this.sourceFloor = sourceFloor;
        this.destinationFloor = destinationFloor;
        this.direction = direction;
        this.requestType = requestType;
        this.timestamp = System.currentTimeMillis();
    }

    public int getSourceFloor() { return sourceFloor; }
    public int getDestinationFloor() { return destinationFloor; }
    public Direction getDirection() { return direction; }
    public RequestType getRequestType() { return requestType; }
    public long getTimestamp() { return timestamp; }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Request other)) return false;
        return sourceFloor == other.sourceFloor &&
               destinationFloor == other.destinationFloor &&
               direction == other.direction;
    }

    @Override
    public int hashCode() {
        return Objects.hash(sourceFloor, destinationFloor, direction);
    }

    @Override
    public String toString() {
        return String.format("Request(src=%d, dest=%d, dir=%s, type=%s)",
                sourceFloor, destinationFloor, direction, requestType);
    }
}

Door

The Door class manages the door mechanism. In our simplified model, open/close are instant transitions. In a real system, these would be asynchronous operations with timers. The elevator keeps a critical invariant: it never moves while the door is open — move() closes the doors before the car leaves a floor.

class Door:
    """Elevator door with open/close state management."""

    def __init__(self):
        self._status = DoorStatus.CLOSED

    @property
    def status(self) -> DoorStatus:
        return self._status

    def is_closed(self) -> bool:
        return self._status == DoorStatus.CLOSED

    def open(self) -> None:
        if self._status == DoorStatus.CLOSED:
            self._status = DoorStatus.OPENING
            # In a real system, this would be async with a timer
            self._status = DoorStatus.OPEN

    def close(self) -> None:
        if self._status == DoorStatus.OPEN:
            self._status = DoorStatus.CLOSING
            self._status = DoorStatus.CLOSED
public class Door {
    private DoorStatus status;

    public Door() {
        this.status = DoorStatus.CLOSED;
    }

    public DoorStatus getStatus() { return status; }

    public boolean isClosed() {
        return status == DoorStatus.CLOSED;
    }

    public void open() {
        if (status == DoorStatus.CLOSED) {
            status = DoorStatus.OPENING;
            status = DoorStatus.OPEN;
        }
    }

    public void close() {
        if (status == DoorStatus.OPEN) {
            status = DoorStatus.CLOSING;
            status = DoorStatus.CLOSED;
        }
    }
}

Scheduling Strategies

Three interchangeable scheduling algorithms implementing the SchedulingStrategy interface. The Strategy Pattern (Fundamentals S12) allows swapping algorithms without modifying the Dispatcher or Elevator classes.

class SchedulingStrategy(ABC):
    """Interface for elevator scheduling algorithms."""

    @abstractmethod
    def select_elevator(self, request: Request,
                        elevators: List['Elevator']) -> Optional['Elevator']:
        """Select the best elevator to handle a hall call."""
        pass

    @abstractmethod
    def get_next_stop(self, elevator: 'Elevator') -> Optional[int]:
        """Determine the next floor this elevator should visit."""
        pass


class FCFSStrategy(SchedulingStrategy):
    """First Come First Served — assign to the least-loaded car, idle ones first; head for the oldest request."""

    def select_elevator(self, request: Request,
                        elevators: List['Elevator']) -> Optional['Elevator']:
        # Pick the idle elevator with the fewest requests, or else the one with fewest requests
        idle = [e for e in elevators if e.state == ElevatorState.IDLE]
        if idle:
            return min(idle, key=lambda e: len(e.requests))
        return min(elevators, key=lambda e: len(e.requests))

    def get_next_stop(self, elevator: 'Elevator') -> Optional[int]:
        if not elevator.requests:
            return None
        return elevator.requests[0].destination_floor


class SCANStrategy(SchedulingStrategy):
    """SCAN — sweep in current direction, reverse at building edge."""

    def __init__(self, min_floor: int, max_floor: int):
        self.min_floor = min_floor  # the building's edges: the sweep goes on to them before reversing
        self.max_floor = max_floor

    def select_elevator(self, request: Request,
                        elevators: List['Elevator']) -> Optional['Elevator']:
        best = None
        best_score = float('inf')

        for elevator in elevators:
            if elevator.state == ElevatorState.IDLE:
                score = abs(elevator.current_floor - request.source_floor)
            elif (elevator.direction == Direction.UP and
                  request.direction == Direction.UP and
                  elevator.current_floor <= request.source_floor):
                # Elevator going up, request is up, elevator is below — on the way
                score = request.source_floor - elevator.current_floor
            elif (elevator.direction == Direction.DOWN and
                  request.direction == Direction.DOWN and
                  elevator.current_floor >= request.source_floor):
                score = elevator.current_floor - request.source_floor
            else:
                # Elevator going wrong direction — penalize
                score = 1000 + abs(elevator.current_floor - request.source_floor)

            # Equal scores: the car with fewer pending requests (R4)
            if score < best_score or (score == best_score and len(elevator.requests) < len(best.requests)):
                best_score = score
                best = elevator

        return best

    def get_next_stop(self, elevator: 'Elevator') -> Optional[int]:
        if not elevator.requests:
            return None

        floors = [r.destination_floor for r in elevator.requests]
        current = elevator.current_floor
        direction = elevator.direction

        if direction == Direction.UP:
            up_floors = sorted([f for f in floors if f >= current])
            if up_floors:
                return up_floors[0]
            if current < self.max_floor:
                return self.max_floor  # nothing above: sweep on to the top floor, then reverse
            down_floors = sorted([f for f in floors if f < current], reverse=True)
            return down_floors[0] if down_floors else None

        elif direction == Direction.DOWN:
            down_floors = sorted([f for f in floors if f <= current], reverse=True)
            if down_floors:
                return down_floors[0]
            if current > self.min_floor:
                return self.min_floor  # nothing below: sweep on to the bottom floor, then reverse
            up_floors = sorted([f for f in floors if f > current])
            return up_floors[0] if up_floors else None

        else:  # IDLE
            return min(floors, key=lambda f: abs(f - current))


class LOOKStrategy(SchedulingStrategy):
    """LOOK — like SCAN but reverses at the last request, not building edge."""

    def select_elevator(self, request: Request,
                        elevators: List['Elevator']) -> Optional['Elevator']:
        # Same selection logic as SCAN — LOOK differs in stop ordering, not dispatch
        best = None
        best_score = float('inf')

        for elevator in elevators:
            if elevator.state == ElevatorState.IDLE:
                score = abs(elevator.current_floor - request.source_floor)
            elif (elevator.direction == Direction.UP and
                  request.direction == Direction.UP and
                  elevator.current_floor <= request.source_floor):
                score = request.source_floor - elevator.current_floor
            elif (elevator.direction == Direction.DOWN and
                  request.direction == Direction.DOWN and
                  elevator.current_floor >= request.source_floor):
                score = elevator.current_floor - request.source_floor
            else:
                score = 1000 + abs(elevator.current_floor - request.source_floor)

            # Equal scores: the car with fewer pending requests (R4)
            if score < best_score or (score == best_score and len(elevator.requests) < len(best.requests)):
                best_score = score
                best = elevator

        return best

    def get_next_stop(self, elevator: 'Elevator') -> Optional[int]:
        if not elevator.requests:
            return None

        floors = [r.destination_floor for r in elevator.requests]
        current = elevator.current_floor
        direction = elevator.direction

        if direction == Direction.UP:
            up_floors = sorted([f for f in floors if f >= current])
            if up_floors:
                return up_floors[0]
            # LOOK: reverse immediately (no trip to building edge)
            down_floors = sorted([f for f in floors if f < current], reverse=True)
            return down_floors[0] if down_floors else None

        elif direction == Direction.DOWN:
            down_floors = sorted([f for f in floors if f <= current], reverse=True)
            if down_floors:
                return down_floors[0]
            up_floors = sorted([f for f in floors if f > current])
            return up_floors[0] if up_floors else None

        else:  # IDLE
            return min(floors, key=lambda f: abs(f - current))
// --- Scheduling Strategy Interface ---

public interface SchedulingStrategy {
    Elevator selectElevator(Request request, List<Elevator> elevators);
    int getNextStop(Elevator elevator);  // returns -1 if no requests
}

// --- FCFS Strategy ---

public class FCFSStrategy implements SchedulingStrategy {
    @Override
    public Elevator selectElevator(Request request, List<Elevator> elevators) {
        // The idle elevator with the fewest requests, or else the one with fewest requests
        return elevators.stream()
                .filter(e -> e.getState() == ElevatorState.IDLE)
                .min(Comparator.comparingInt(e -> e.getRequests().size()))
                .orElse(elevators.stream()
                        .min(Comparator.comparingInt(e -> e.getRequests().size()))
                        .orElse(null));
    }

    @Override
    public int getNextStop(Elevator elevator) {
        if (elevator.getRequests().isEmpty()) return -1;
        return elevator.getRequests().get(0).getDestinationFloor();
    }
}

// --- SCAN Strategy ---

public class SCANStrategy implements SchedulingStrategy {
    private final int minFloor;  // the building's edges: the sweep goes on to them before reversing
    private final int maxFloor;

    public SCANStrategy(int minFloor, int maxFloor) {
        this.minFloor = minFloor;
        this.maxFloor = maxFloor;
    }

    @Override
    public Elevator selectElevator(Request request, List<Elevator> elevators) {
        Elevator best = null;
        int bestScore = Integer.MAX_VALUE;

        for (Elevator elevator : elevators) {
            int score;
            if (elevator.getState() == ElevatorState.IDLE) {
                score = Math.abs(elevator.getCurrentFloor() - request.getSourceFloor());
            } else if (elevator.getDirection() == Direction.UP &&
                       request.getDirection() == Direction.UP &&
                       elevator.getCurrentFloor() <= request.getSourceFloor()) {
                score = request.getSourceFloor() - elevator.getCurrentFloor();
            } else if (elevator.getDirection() == Direction.DOWN &&
                       request.getDirection() == Direction.DOWN &&
                       elevator.getCurrentFloor() >= request.getSourceFloor()) {
                score = elevator.getCurrentFloor() - request.getSourceFloor();
            } else {
                score = 1000 + Math.abs(elevator.getCurrentFloor() - request.getSourceFloor());
            }

            // Equal scores: the car with fewer pending requests (R4)
            if (score < bestScore || (score == bestScore && elevator.getRequests().size() < best.getRequests().size())) {
                bestScore = score;
                best = elevator;
            }
        }
        return best;
    }

    @Override
    public int getNextStop(Elevator elevator) {
        List<Request> requests = elevator.getRequests();
        if (requests.isEmpty()) return -1;

        int current = elevator.getCurrentFloor();
        Direction dir = elevator.getDirection();

        if (dir == Direction.UP) {
            OptionalInt next = requests.stream()
                    .mapToInt(Request::getDestinationFloor)
                    .filter(f -> f >= current).min();
            if (next.isPresent()) return next.getAsInt();
            if (current < maxFloor) return maxFloor;  // nothing above: sweep on to the top floor, then reverse

            return requests.stream()
                    .mapToInt(Request::getDestinationFloor)
                    .filter(f -> f < current).max().orElse(-1);

        } else if (dir == Direction.DOWN) {
            OptionalInt next = requests.stream()
                    .mapToInt(Request::getDestinationFloor)
                    .filter(f -> f <= current).max();
            if (next.isPresent()) return next.getAsInt();
            if (current > minFloor) return minFloor;  // nothing below: sweep on to the bottom floor, then reverse

            return requests.stream()
                    .mapToInt(Request::getDestinationFloor)
                    .filter(f -> f > current).min().orElse(-1);

        } else {
            return requests.stream()
                    .map(Request::getDestinationFloor)
                    .min(Comparator.comparingInt(f -> Math.abs(f - current)))
                    .orElse(-1);
        }
    }
}

// --- LOOK Strategy ---

public class LOOKStrategy implements SchedulingStrategy {
    @Override
    public Elevator selectElevator(Request request, List<Elevator> elevators) {
        // Same dispatch logic as SCAN
        Elevator best = null;
        int bestScore = Integer.MAX_VALUE;

        for (Elevator elevator : elevators) {
            int score;
            if (elevator.getState() == ElevatorState.IDLE) {
                score = Math.abs(elevator.getCurrentFloor() - request.getSourceFloor());
            } else if (elevator.getDirection() == Direction.UP &&
                       request.getDirection() == Direction.UP &&
                       elevator.getCurrentFloor() <= request.getSourceFloor()) {
                score = request.getSourceFloor() - elevator.getCurrentFloor();
            } else if (elevator.getDirection() == Direction.DOWN &&
                       request.getDirection() == Direction.DOWN &&
                       elevator.getCurrentFloor() >= request.getSourceFloor()) {
                score = elevator.getCurrentFloor() - request.getSourceFloor();
            } else {
                score = 1000 + Math.abs(elevator.getCurrentFloor() - request.getSourceFloor());
            }
            // Equal scores: the car with fewer pending requests (R4)
            if (score < bestScore || (score == bestScore && elevator.getRequests().size() < best.getRequests().size())) {
                bestScore = score;
                best = elevator;
            }
        }
        return best;
    }

    @Override
    public int getNextStop(Elevator elevator) {
        List<Request> requests = elevator.getRequests();
        if (requests.isEmpty()) return -1;

        int current = elevator.getCurrentFloor();
        Direction dir = elevator.getDirection();

        if (dir == Direction.UP) {
            OptionalInt next = requests.stream()
                    .mapToInt(Request::getDestinationFloor)
                    .filter(f -> f >= current).min();
            if (next.isPresent()) return next.getAsInt();
            return requests.stream()
                    .mapToInt(Request::getDestinationFloor)
                    .filter(f -> f < current).max().orElse(-1);
        } else if (dir == Direction.DOWN) {
            OptionalInt next = requests.stream()
                    .mapToInt(Request::getDestinationFloor)
                    .filter(f -> f <= current).max();
            if (next.isPresent()) return next.getAsInt();
            return requests.stream()
                    .mapToInt(Request::getDestinationFloor)
                    .filter(f -> f > current).min().orElse(-1);
        } else {
            return requests.stream()
                    .map(Request::getDestinationFloor)
                    .min(Comparator.comparingInt(f -> Math.abs(f - current)))
                    .orElse(-1);
        }
    }
}

Elevator

The Elevator class is the heart of the system. It manages its current floor, direction, state, door, request queue, and notifies observers (floor displays) when it moves and when it goes idle. The move() method advances the elevator one floor (closing the doors first if a stop left them open) and the stop() method opens the doors and serves the floor — they stay open until the car moves on, or close at once if nothing is left. The scheduling strategy determines WHERE to go; the elevator handles HOW to get there.

class ElevatorObserver(ABC):
    """Observer interface for elevator state changes."""

    @abstractmethod
    def on_elevator_moved(self, elevator_id: int, floor: int,
                          direction: Direction) -> None:
        pass


class Elevator:
    """An elevator car with position, direction, door, and request management."""

    def __init__(self, elevator_id: int, current_floor: int = 1):
        self.id = elevator_id
        self.current_floor = current_floor
        self.direction = Direction.IDLE
        self.state = ElevatorState.IDLE
        self.door = Door()
        self.requests: List[Request] = []
        self.panel = ElevatorPanel(self)
        self._observers: List[ElevatorObserver] = []

    def add_observer(self, observer: ElevatorObserver) -> None:
        self._observers.append(observer)
        observer.on_elevator_moved(self.id, self.current_floor, self.direction)  # where the car is now

    def remove_observer(self, observer: ElevatorObserver) -> None:
        self._observers.remove(observer)

    def _notify_observers(self) -> None:
        for observer in self._observers:
            observer.on_elevator_moved(self.id, self.current_floor, self.direction)

    def add_request(self, request: Request) -> None:
        """Add a request to this elevator's queue if not duplicate."""
        if request not in self.requests:
            self.requests.append(request)

    def remove_request_for_floor(self, floor: int) -> None:
        """Remove all requests targeting a specific floor."""
        self.requests = [r for r in self.requests
                         if r.destination_floor != floor]

    def has_requests(self) -> bool:
        return len(self.requests) > 0

    def move(self, strategy: SchedulingStrategy) -> None:
        """Advance the elevator one step using the scheduling strategy."""
        if not self.has_requests():
            self.state = ElevatorState.IDLE
            self.direction = Direction.IDLE
            return

        next_stop = strategy.get_next_stop(self)
        if next_stop is None:
            self.state = ElevatorState.IDLE
            self.direction = Direction.IDLE
            return

        if next_stop != self.current_floor:
            self.door.close()  # Cannot move with open doors: they close as the car leaves

        # Determine direction
        if next_stop > self.current_floor:
            self.direction = Direction.UP
            self.state = ElevatorState.MOVING_UP
            self.current_floor += 1
        elif next_stop < self.current_floor:
            self.direction = Direction.DOWN
            self.state = ElevatorState.MOVING_DOWN
            self.current_floor -= 1
        else:
            # Already at the target floor
            self.stop()
            return

        self._notify_observers()

        # Check if we should stop at this floor
        if self.should_stop(self.current_floor):
            self.stop()

    def should_stop(self, floor: int) -> bool:
        """Check if the elevator should stop at this floor."""
        return any(r.destination_floor == floor for r in self.requests)

    def stop(self) -> None:
        """Stop at the current floor — open doors, serve requests; close them if nothing is left."""
        self.state = ElevatorState.DOOR_OPEN
        self.door.open()

        # Serve all requests for this floor
        self.remove_request_for_floor(self.current_floor)
        self.panel.clear_floor(self.current_floor)

        # Decide next state
        if not self.has_requests():
            self.door.close()
            self.state = ElevatorState.IDLE
            self.direction = Direction.IDLE
            self._notify_observers()  # the displays show it idle
        # Otherwise it stays DOOR_OPEN, doors open, until move() closes them and leaves

    def __repr__(self) -> str:
        return (f"Elevator(id={self.id}, floor={self.current_floor}, "
                f"dir={self.direction.value}, state={self.state.value}, "
                f"requests={len(self.requests)})")
// --- Observer Interface ---

public interface ElevatorObserver {
    void onElevatorMoved(int elevatorId, int floor, Direction direction);
}

// --- Elevator ---

public class Elevator {
    private final int id;
    private int currentFloor;
    private Direction direction;
    private ElevatorState state;
    private final Door door;
    private final List<Request> requests;
    private final ElevatorPanel panel;
    private final List<ElevatorObserver> observers;

    public Elevator(int id, int startFloor) {
        this.id = id;
        this.currentFloor = startFloor;
        this.direction = Direction.IDLE;
        this.state = ElevatorState.IDLE;
        this.door = new Door();
        this.requests = new ArrayList<>();
        this.panel = new ElevatorPanel(this);
        this.observers = new ArrayList<>();
    }

    public int getId() { return id; }
    public int getCurrentFloor() { return currentFloor; }
    public Direction getDirection() { return direction; }
    public ElevatorState getState() { return state; }
    public List<Request> getRequests() { return Collections.unmodifiableList(requests); }
    public ElevatorPanel getPanel() { return panel; }

    public void addObserver(ElevatorObserver observer) {
        observers.add(observer);
        observer.onElevatorMoved(id, currentFloor, direction);  // where the car is now
    }
    public void removeObserver(ElevatorObserver observer) { observers.remove(observer); }

    private void notifyObservers() {
        for (ElevatorObserver obs : observers) {
            obs.onElevatorMoved(id, currentFloor, direction);
        }
    }

    public void addRequest(Request request) {
        if (!requests.contains(request)) {
            requests.add(request);
        }
    }

    public void removeRequestForFloor(int floor) {
        requests.removeIf(r -> r.getDestinationFloor() == floor);
    }

    public boolean hasRequests() { return !requests.isEmpty(); }

    public void move(SchedulingStrategy strategy) {
        if (!hasRequests()) {
            state = ElevatorState.IDLE;
            direction = Direction.IDLE;
            return;
        }

        int nextStop = strategy.getNextStop(this);
        if (nextStop == -1) {
            state = ElevatorState.IDLE;
            direction = Direction.IDLE;
            return;
        }

        if (nextStop != currentFloor) {
            door.close();  // Cannot move with open doors: they close as the car leaves
        }

        if (nextStop > currentFloor) {
            direction = Direction.UP;
            state = ElevatorState.MOVING_UP;
            currentFloor++;
        } else if (nextStop < currentFloor) {
            direction = Direction.DOWN;
            state = ElevatorState.MOVING_DOWN;
            currentFloor--;
        } else {
            stop();
            return;
        }

        notifyObservers();

        if (shouldStop(currentFloor)) {
            stop();
        }
    }

    public boolean shouldStop(int floor) {
        return requests.stream()
                .anyMatch(r -> r.getDestinationFloor() == floor);
    }

    public void stop() {
        state = ElevatorState.DOOR_OPEN;
        door.open();

        removeRequestForFloor(currentFloor);
        panel.clearFloor(currentFloor);

        if (!hasRequests()) {
            door.close();
            state = ElevatorState.IDLE;
            direction = Direction.IDLE;
            notifyObservers();  // the displays show it idle
        }
        // Otherwise it stays DOOR_OPEN, doors open, until move() closes them and leaves
    }

    @Override
    public String toString() {
        return String.format("Elevator(id=%d, floor=%d, dir=%s, state=%s, reqs=%d)",
                id, currentFloor, direction, state, requests.size());
    }
}

Floor Components — HallButton, FloorDisplay, ElevatorPanel

These three classes represent the user-facing components:

  • HallButton — the UP/DOWN button on each floor that creates hall call requests
  • FloorDisplay — shows elevator positions and directions, updated via Observer pattern
  • ElevatorPanel — the button panel inside each elevator for cabin calls
class HallButton:
    """UP/DOWN button on a floor for making hall calls."""

    def __init__(self, floor: int, direction: Direction):
        self.floor = floor
        self.direction = direction
        self.is_pressed = False

    def press(self) -> Optional[Request]:
        """Press the button — returns a Request if not already pressed."""
        if self.is_pressed:
            return None  # Duplicate request prevention (R10)
        self.is_pressed = True
        return Request(
            source_floor=self.floor,
            destination_floor=self.floor,  # Hall call: dest is the source floor
            direction=self.direction,
            request_type=RequestType.HALL_CALL
        )

    def reset(self) -> None:
        """Reset the button after the elevator arrives."""
        self.is_pressed = False


class FloorDisplay(ElevatorObserver):
    """Display panel on a floor showing elevator positions and directions."""

    def __init__(self, floor: int):
        self.floor = floor
        self._elevator_positions: Dict[int, int] = {}  # elevator_id -> floor
        self._elevator_directions: Dict[int, Direction] = {}  # elevator_id -> direction

    def on_elevator_moved(self, elevator_id: int, floor: int,
                          direction: Direction) -> None:
        self._elevator_positions[elevator_id] = floor
        self._elevator_directions[elevator_id] = direction

    def display(self) -> str:
        lines = [f"=== Floor {self.floor} Display ==="]
        for eid in sorted(self._elevator_positions.keys()):
            pos = self._elevator_positions[eid]
            dir_symbol = {Direction.UP: "▲", Direction.DOWN: "▼",
                          Direction.IDLE: "●"}
            symbol = dir_symbol.get(self._elevator_directions.get(eid, Direction.IDLE), "●")
            lines.append(f"  Elevator {eid}: Floor {pos} {symbol}")
        return "\n".join(lines)


class ElevatorPanel:
    """Button panel inside an elevator for making cabin calls."""

    def __init__(self, elevator: 'Elevator'):
        self._elevator = elevator
        self._pressed_floors: Set[int] = set()

    def press_floor(self, floor: int) -> Optional[Request]:
        """Press a floor button inside the elevator."""
        if floor in self._pressed_floors:
            return None  # Already pressed
        if floor == self._elevator.current_floor:
            return None  # Already at this floor

        self._pressed_floors.add(floor)

        direction = Direction.UP if floor > self._elevator.current_floor else Direction.DOWN
        return Request(
            source_floor=self._elevator.current_floor,
            destination_floor=floor,
            direction=direction,
            request_type=RequestType.CABIN_CALL
        )

    def clear_floor(self, floor: int) -> None:
        """Clear a floor button when the elevator arrives."""
        self._pressed_floors.discard(floor)
// --- HallButton ---

public class HallButton {
    private final int floor;
    private final Direction direction;
    private boolean isPressed;

    public HallButton(int floor, Direction direction) {
        this.floor = floor;
        this.direction = direction;
        this.isPressed = false;
    }

    public Request press() {
        if (isPressed) return null;  // Duplicate prevention (R10)
        isPressed = true;
        return new Request(floor, floor, direction, RequestType.HALL_CALL);
    }

    public void reset() { isPressed = false; }
    public boolean isPressed() { return isPressed; }
}

// --- FloorDisplay ---

public class FloorDisplay implements ElevatorObserver {
    private final int floor;
    private final Map<Integer, Integer> elevatorPositions = new HashMap<>();
    private final Map<Integer, Direction> elevatorDirections = new HashMap<>();

    public FloorDisplay(int floor) {
        this.floor = floor;
    }

    @Override
    public void onElevatorMoved(int elevatorId, int floor, Direction direction) {
        elevatorPositions.put(elevatorId, floor);
        elevatorDirections.put(elevatorId, direction);
    }

    public String display() {
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("=== Floor %d Display ===%n", floor));
        for (int eid : new TreeSet<>(elevatorPositions.keySet())) {
            int pos = elevatorPositions.get(eid);
            Direction dir = elevatorDirections.getOrDefault(eid, Direction.IDLE);
            String symbol = switch (dir) {
                case UP -> "▲";
                case DOWN -> "▼";
                case IDLE -> "●";
            };
            sb.append(String.format("  Elevator %d: Floor %d %s%n", eid, pos, symbol));
        }
        return sb.toString();
    }
}

// --- ElevatorPanel ---

public class ElevatorPanel {
    private final Elevator elevator;
    private final Set<Integer> pressedFloors = new HashSet<>();

    public ElevatorPanel(Elevator elevator) {
        this.elevator = elevator;
    }

    public Request pressFloor(int floor) {
        if (pressedFloors.contains(floor)) return null;
        if (floor == elevator.getCurrentFloor()) return null;

        pressedFloors.add(floor);
        Direction dir = floor > elevator.getCurrentFloor() ? Direction.UP : Direction.DOWN;
        return new Request(elevator.getCurrentFloor(), floor, dir, RequestType.CABIN_CALL);
    }

    public void clearFloor(int floor) {
        pressedFloors.remove(floor);
    }
}

Dispatcher and ElevatorSystem

The Dispatcher receives hall call requests and uses the scheduling strategy to assign them to the optimal elevator. The ElevatorSystem is the top-level orchestrator that composes all components and drives the simulation loop. Each step also frees the hall button and the Dispatcher's record of every hall call a stop has served, so that call can be made again (R10 blocks duplicates only while a call is waiting).

class Dispatcher:
    """Assigns hall calls to the optimal elevator using the scheduling strategy."""

    def __init__(self, elevators: List[Elevator], strategy: SchedulingStrategy):
        self._elevators = elevators
        self._strategy = strategy
        self._pending_requests: Set[Request] = set()

    def set_strategy(self, strategy: SchedulingStrategy) -> None:
        """Swap the scheduling algorithm at runtime."""
        self._strategy = strategy

    @property
    def strategy(self) -> SchedulingStrategy:
        return self._strategy

    def dispatch(self, request: Request) -> Optional[Elevator]:
        """Assign a request to the best elevator."""
        if request in self._pending_requests:
            return None  # Duplicate prevention (R10)

        elevator = self._strategy.select_elevator(request, self._elevators)
        if elevator is not None:
            elevator.add_request(request)
            self._pending_requests.add(request)
        return elevator

    def mark_served(self, request: Request) -> None:
        self._pending_requests.discard(request)


class Floor:
    """A building floor with hall buttons and a display."""

    def __init__(self, floor_number: int, is_bottom: bool = False,
                 is_top: bool = False):
        self.floor_number = floor_number
        self.up_button = None if is_top else HallButton(floor_number, Direction.UP)
        self.down_button = None if is_bottom else HallButton(floor_number, Direction.DOWN)
        self.display = FloorDisplay(floor_number)

    def press_up(self) -> Optional[Request]:
        return self.up_button.press() if self.up_button else None

    def press_down(self) -> Optional[Request]:
        return self.down_button.press() if self.down_button else None

    def reset_button(self, direction: Direction) -> None:
        """A car has stopped for this floor's call in this direction: the button is free again."""
        button = self.up_button if direction == Direction.UP else self.down_button
        if button:
            button.reset()


class ElevatorSystem:
    """Top-level system that composes elevators, floors, and the dispatcher."""

    def __init__(self, num_floors: int, num_elevators: int,
                 strategy: SchedulingStrategy):
        # Create floors
        self.floors: List[Floor] = []
        for i in range(1, num_floors + 1):
            is_bottom = (i == 1)
            is_top = (i == num_floors)
            self.floors.append(Floor(i, is_bottom=is_bottom, is_top=is_top))

        # Create elevators (all start at floor 1)
        self.elevators: List[Elevator] = []
        for i in range(num_elevators):
            elevator = Elevator(elevator_id=i + 1, current_floor=1)
            # Register all floor displays as observers
            for floor in self.floors:
                elevator.add_observer(floor.display)
            self.elevators.append(elevator)

        # Create dispatcher
        self.dispatcher = Dispatcher(self.elevators, strategy)

    def add_hall_call(self, floor_number: int, direction: Direction) -> Optional[Elevator]:
        """Process a hall call from a floor."""
        floor = self.floors[floor_number - 1]
        if direction == Direction.UP:
            request = floor.press_up()
        else:
            request = floor.press_down()

        if request is None:
            return None  # Button already pressed

        return self.dispatcher.dispatch(request)

    def add_cabin_call(self, elevator_id: int, destination_floor: int) -> None:
        """Process a cabin call from inside an elevator."""
        elevator = self.elevators[elevator_id - 1]
        request = elevator.panel.press_floor(destination_floor)
        if request is not None:
            elevator.add_request(request)

    def step(self) -> None:
        """Advance the simulation by one time unit — each elevator moves one floor."""
        for elevator in self.elevators:
            waiting = list(elevator.requests)
            elevator.move(self.dispatcher.strategy)
            for request in waiting:
                if request.request_type == RequestType.HALL_CALL and request not in elevator.requests:
                    self._hall_call_served(request)

    def _hall_call_served(self, request: Request) -> None:
        """The car stopped for this hall call: its button and the dispatcher take calls again."""
        self.floors[request.source_floor - 1].reset_button(request.direction)
        self.dispatcher.mark_served(request)

    def display_status(self) -> str:
        """Display the current status of all elevators."""
        lines = ["=== Elevator System Status ==="]
        for e in self.elevators:
            lines.append(f"  {e}")
        return "\n".join(lines)
// --- Dispatcher ---

public class Dispatcher {
    private final List<Elevator> elevators;
    private SchedulingStrategy strategy;
    private final Set<Request> pendingRequests = new HashSet<>();

    public Dispatcher(List<Elevator> elevators, SchedulingStrategy strategy) {
        this.elevators = elevators;
        this.strategy = strategy;
    }

    public void setStrategy(SchedulingStrategy strategy) {
        this.strategy = strategy;
    }

    public SchedulingStrategy getStrategy() { return strategy; }

    public Elevator dispatch(Request request) {
        if (pendingRequests.contains(request)) return null;

        Elevator elevator = strategy.selectElevator(request, elevators);
        if (elevator != null) {
            elevator.addRequest(request);
            pendingRequests.add(request);
        }
        return elevator;
    }

    public void markServed(Request request) {
        pendingRequests.remove(request);
    }
}

// --- Floor ---

public class Floor {
    private final int floorNumber;
    private final HallButton upButton;
    private final HallButton downButton;
    private final FloorDisplay display;

    public Floor(int floorNumber, boolean isBottom, boolean isTop) {
        this.floorNumber = floorNumber;
        this.upButton = isTop ? null : new HallButton(floorNumber, Direction.UP);
        this.downButton = isBottom ? null : new HallButton(floorNumber, Direction.DOWN);
        this.display = new FloorDisplay(floorNumber);
    }

    public int getFloorNumber() { return floorNumber; }
    public FloorDisplay getDisplay() { return display; }

    public Request pressUp() {
        return upButton != null ? upButton.press() : null;
    }

    public Request pressDown() {
        return downButton != null ? downButton.press() : null;
    }

    /** A car has stopped for this floor's call in this direction: the button is free again. */
    public void resetButton(Direction direction) {
        HallButton button = direction == Direction.UP ? upButton : downButton;
        if (button != null) button.reset();
    }
}

// --- ElevatorSystem ---

public class ElevatorSystem {
    private final List<Floor> floors;
    private final List<Elevator> elevators;
    private final Dispatcher dispatcher;

    public ElevatorSystem(int numFloors, int numElevators,
                          SchedulingStrategy strategy) {
        floors = new ArrayList<>();
        for (int i = 1; i <= numFloors; i++) {
            floors.add(new Floor(i, i == 1, i == numFloors));
        }

        elevators = new ArrayList<>();
        for (int i = 0; i < numElevators; i++) {
            Elevator elevator = new Elevator(i + 1, 1);
            for (Floor floor : floors) {
                elevator.addObserver(floor.getDisplay());
            }
            elevators.add(elevator);
        }

        dispatcher = new Dispatcher(elevators, strategy);
    }

    public Elevator addHallCall(int floorNumber, Direction direction) {
        Floor floor = floors.get(floorNumber - 1);
        Request request = (direction == Direction.UP)
                ? floor.pressUp() : floor.pressDown();
        if (request == null) return null;
        return dispatcher.dispatch(request);
    }

    public void addCabinCall(int elevatorId, int destinationFloor) {
        Elevator elevator = elevators.get(elevatorId - 1);
        Request request = elevator.getPanel().pressFloor(destinationFloor);
        if (request != null) {
            elevator.addRequest(request);
        }
    }

    public void step() {
        for (Elevator elevator : elevators) {
            List<Request> waiting = new ArrayList<>(elevator.getRequests());
            elevator.move(dispatcher.getStrategy());
            for (Request request : waiting) {
                if (request.getRequestType() == RequestType.HALL_CALL && !elevator.getRequests().contains(request)) {
                    hallCallServed(request);
                }
            }
        }
    }

    /** The car stopped for this hall call: its button and the dispatcher take calls again. */
    private void hallCallServed(Request request) {
        floors.get(request.getSourceFloor() - 1).resetButton(request.getDirection());
        dispatcher.markServed(request);
    }

    public String displayStatus() {
        StringBuilder sb = new StringBuilder("=== Elevator System Status ===\n");
        for (Elevator e : elevators) {
            sb.append("  ").append(e).append("\n");
        }
        return sb.toString();
    }

    public List<Elevator> getElevators() { return elevators; }
    public List<Floor> getFloors() { return floors; }
    public Dispatcher getDispatcher() { return dispatcher; }
}

Usage Example

Let's see the complete system in action with a realistic scenario: a 10-floor building with 2 elevators using the LOOK scheduling algorithm.

# === Elevator System — Usage Example ===

# Create a 10-floor building with 2 elevators using LOOK scheduling
system = ElevatorSystem(
    num_floors=10,
    num_elevators=2,
    strategy=LOOKStrategy()
)

print("Initial state:")
print(system.display_status())
# Both elevators at floor 1, IDLE

# Scenario: hall calls from three floors — two going up, one going down
print("\n--- Hall calls arrive ---")

# Person on floor 3 presses UP
result = system.add_hall_call(3, Direction.UP)
print(f"Floor 3 UP → assigned to Elevator {result.id if result else 'N/A'}")

# Person on floor 7 presses DOWN
result = system.add_hall_call(7, Direction.DOWN)
print(f"Floor 7 DOWN → assigned to Elevator {result.id if result else 'N/A'}")

# Person on floor 5 presses UP
result = system.add_hall_call(5, Direction.UP)
print(f"Floor 5 UP → assigned to Elevator {result.id if result else 'N/A'}")

print("\n--- Simulation begins ---")

# Run the simulation for several steps
for step in range(1, 15):
    system.step()
    print(f"\nStep {step}:")
    print(system.display_status())

    # Simulate cabin calls: when elevator 1 stops at floor 3, the passenger presses 8
    if (system.elevators[0].current_floor == 3 and
            system.elevators[0].state == ElevatorState.DOOR_OPEN):
        system.add_cabin_call(1, 8)
        print("  → Passenger in Elevator 1 presses floor 8")

    # Check if all requests are served
    all_idle = all(e.state == ElevatorState.IDLE for e in system.elevators)
    if all_idle and step > 1:
        print("\n✓ All requests served!")
        break

# Display final floor display from floor 5
print("\n" + system.floors[4].display.display())
public class ElevatorDemo {
    public static void main(String[] args) {
        // Create a 10-floor building with 2 elevators using LOOK
        ElevatorSystem system = new ElevatorSystem(10, 2, new LOOKStrategy());

        System.out.println("Initial state:");
        System.out.println(system.displayStatus());

        // Hall calls from various floors
        System.out.println("--- Hall calls arrive ---");

        Elevator e1 = system.addHallCall(3, Direction.UP);
        System.out.printf("Floor 3 UP → Elevator %d%n", e1 != null ? e1.getId() : -1);

        Elevator e2 = system.addHallCall(7, Direction.DOWN);
        System.out.printf("Floor 7 DOWN → Elevator %d%n", e2 != null ? e2.getId() : -1);

        Elevator e3 = system.addHallCall(5, Direction.UP);
        System.out.printf("Floor 5 UP → Elevator %d%n", e3 != null ? e3.getId() : -1);

        System.out.println("\n--- Simulation ---");

        for (int step = 1; step <= 14; step++) {
            system.step();
            System.out.printf("%nStep %d:%n", step);
            System.out.println(system.displayStatus());

            // Cabin call: when elevator 1 stops at floor 3
            Elevator elev1 = system.getElevators().get(0);
            if (elev1.getCurrentFloor() == 3 &&
                elev1.getState() == ElevatorState.DOOR_OPEN) {
                system.addCabinCall(1, 8);
                System.out.println("  → Passenger in Elevator 1 presses floor 8");
            }

            boolean allIdle = system.getElevators().stream()
                    .allMatch(e -> e.getState() == ElevatorState.IDLE);
            if (allIdle && step > 1) {
                System.out.println("\n✓ All requests served!");
                break;
            }
        }

        // Floor 5 display
        System.out.println(system.getFloors().get(4).getDisplay().display());
    }
}