Skip to main content

Design Patterns Applied

Editorial

Patterns Overview

Our Elevator System uses three design patterns, each solving a distinct problem:

PatternProblem SolvedApplied To
StrategyMultiple scheduling algorithms that must be interchangeable at runtimeSchedulingStrategy → FCFSStrategy, SCANStrategy, LOOKStrategy
StateElevator behavior changes dramatically based on its current stateElevatorState enum driving transitions in Elevator.move()
ObserverFloor displays must update automatically when elevators moveElevatorObserver → FloorDisplay, Elevator._notify_observers()

For each pattern, we'll examine: what problem it solves, how we applied it, WHY we chose it over alternatives, and what the code looks like WITHOUT the pattern.

Strategy Pattern — Scheduling Algorithms

The Problem

We need three scheduling algorithms (FCFS, SCAN, LOOK) and the system should be able to switch between them at runtime. Buildings might use FCFS during low traffic and LOOK during rush hour.

Without Strategy, the Dispatcher would need if/else branches for every algorithm:

# BAD: Without Strategy Pattern — scheduling logic hardcoded in Dispatcher
class Dispatcher:
    def __init__(self, elevators, algorithm_name: str):
        self._elevators = elevators
        self._algorithm = algorithm_name  # "fcfs", "scan", "look"

    def dispatch(self, request):
        # Branching for every algorithm — violates Open/Closed Principle
        if self._algorithm == "fcfs":
            # FCFS logic...
            idle = [e for e in self._elevators if e.state == ElevatorState.IDLE]
            return idle[0] if idle else self._elevators[0]
        elif self._algorithm == "scan":
            # SCAN logic — 30+ lines of scoring...
            best = None
            for elevator in self._elevators:
                # ... complex scoring logic ...
                pass
            return best
        elif self._algorithm == "look":
            # LOOK logic — similar to SCAN but different reversal...
            pass
        # Adding a new algorithm means modifying this class!
        else:
            raise ValueError(f"Unknown algorithm: {self._algorithm}")

How We Applied It

The Strategy Pattern extracts each algorithm into its own class behind a common interface:

  • Context: Dispatcher holds a reference to SchedulingStrategy; each step, ElevatorSystem hands the same strategy to every Elevator.move()
  • Strategy interface: SchedulingStrategy with select_elevator() and get_next_stop()
  • Concrete strategies: FCFSStrategy, SCANStrategy, LOOKStrategy

Switching is one line: dispatcher.set_strategy(LOOKStrategy())

Strategy Pattern applied to the elevator scheduling: the Dispatcher holds one SchedulingStrategy (_strategy, set_strategy, dispatch) — an association; each Elevator's move(strategy) is handed the same one — a «uses» dependency; the abstract SchedulingStrategy declares select_elevator(request, elevators) and get_next_stop(elevator), and FCFSStrategy, SCANStrategy (min_floor, max_floor) and LOOKStrategy extend it; a note: new algorithms require only a new class, no changes to Dispatcher or to Elevator

Why Strategy and Not Alternatives

Why not Template Method? Template Method uses inheritance — you'd need FCFSDispatcher, SCANDispatcher, LOOKDispatcher. This prevents runtime switching and creates class explosion. Strategy uses composition, allowing the same Dispatcher instance to change algorithms.

Why not simple if/else? Violates the Open/Closed Principle. Adding a fourth algorithm (e.g., Destination Dispatch) means modifying the Dispatcher. With Strategy, you create DestinationDispatchStrategy — no existing code changes.

Why not Command Pattern? Command encapsulates a single operation with undo support. Our scheduling algorithms are stateless selection logic, not undoable operations. Strategy is the right fit for interchangeable algorithms.

State Pattern — Elevator Behavior

The Problem

An elevator's behavior depends entirely on its current state. When IDLE, it should accept any request. When MOVING_UP, it should only stop at floors ahead in the upward direction. When DOOR_OPEN, it must never move with its doors open — move() closes them before the car leaves. Without explicit state management, you end up with deeply nested conditionals.

# BAD: Without State Pattern — every method must check every state
class Elevator:
    def move(self):
        if self.state == "idle":
            # Can start moving in any direction
            pass
        elif self.state == "moving_up":
            if self.door_open:
                return  # Can't move with open doors!
            self.current_floor += 1
            if self.should_stop():
                self.state = "door_open"
                # What about closing? Setting timer?
        elif self.state == "moving_down":
            if self.door_open:
                return
            self.current_floor -= 1
            # Duplicate logic from moving_up...
        elif self.state == "door_open":
            return  # Can't move
        # Every new state requires changes to EVERY method

How We Applied It

We use state-driven behavior through the ElevatorState enum and structured transitions in the move() method:

  1. State represented by enum: ElevatorState.IDLE, MOVING_UP, MOVING_DOWN, DOOR_OPEN
  2. Transitions in one place: move() decides from the next stop — it closes the doors and sets MOVING_UP or MOVING_DOWN as the car leaves a floor, stop() sets DOOR_OPEN at a requested floor, and with nothing left the car goes IDLE
  3. Guard conditions: The door must be closed before movement; the elevator must have requests to move
  4. Clean transition logic: state and direction change together — moving sets both, going idle clears both, and a stop keeps the direction for the sweep

This is a simplified State Pattern — instead of separate state classes (which would add complexity for only 4 states), we use the enum with well-structured transition logic. For a system with many more states (e.g., maintenance mode, emergency mode, fire service), extracting into full state classes (Fundamentals S4) would be warranted.

One State at a Time

Run the car and watch the one field that drives it. It is one elevator of the Code Implementation's building, and each Step runs the code's own move() — the lines it ran are lit, in Python or Java. Beside the car's ElevatorState stand the designs this section weighs against it: a class per state, Direction alone, and three booleans. Stop at a floor and Direction still reads UP while the doors are open; set the three booleans free and five of their eight combinations are no state at all. Turn on Ask me first to name the state after each move().

Interactive: the State Pattern as the Elevator System applies it — one car of the Code Implementation's building (LOOK) stepped by its own move() and stop(), the lines each step ran lit in Python or Java. Beside the car's one ElevatorState: the class the lesson's alternative would use (IdleState, MovingUpState, MovingDownState, DoorOpenState), what Direction alone reads (UP or DOWN while the car stands at a stop with its doors open; IDLE when it opened for a call at its own floor), and the three booleans is_moving, is_door_open and is_idle — read off the car exactly one is true; set free, five of their eight combinations are no state. Ask me first names the state after each move(). Six missions.

Why State Pattern and Not Alternatives

Why not full State classes? With only 4 states, creating IdleState, MovingUpState, MovingDownState, DoorOpenState classes would be over-engineering. The enum-based approach is simpler and more readable. If states grew beyond 6-8, extracting to classes would be the right call.

Why not a boolean flag per state? Using is_moving, is_door_open, is_idle booleans leads to invalid combinations (is_moving=True, is_door_open=True). The enum guarantees the elevator is in exactly one state.

Why not just Direction? Direction (UP, DOWN, IDLE) doesn't capture DOOR_OPEN. You'd need extra checks everywhere. The explicit state enum is clearer and safer.

Observer Pattern — Floor Displays

The Problem

Every floor has a display showing where each elevator is and which direction it's heading. When an elevator moves, ALL floor displays must update. Without Observer, the elevator would need to know about every display — a tight coupling nightmare.

# BAD: Without Observer — Elevator directly updates every display
class Elevator:
    def __init__(self, elevator_id, all_floor_displays):  # Must know ALL displays!
        self.id = elevator_id
        self._all_displays = all_floor_displays  # Tight coupling

    def move(self):
        self.current_floor += 1
        # Manually update EVERY display
        for display in self._all_displays:
            display.update(self.id, self.current_floor, self.direction)
        # What if we add lobby screens? Monitoring dashboards?
        # Must modify THIS class every time a new display type appears.

How We Applied It

The Observer Pattern decouples the elevator from its observers:

  • Subject: Elevator maintains a list of ElevatorObserver references
  • Observer interface: ElevatorObserver with on_elevator_moved(elevator_id, floor, direction)
  • Concrete observer: FloorDisplay implements ElevatorObserver
  • Registration: ElevatorSystem.__init__() registers each floor's display with each elevator

The elevator calls _notify_observers() after every move, and when it goes idle at its last stop. It doesn't know or care what the observers do with the information. Adding a new observer type (e.g., a monitoring dashboard) requires zero changes to the Elevator class.

# WITH Observer — Elevator only knows about the Observer interface
class Elevator:
    def __init__(self, elevator_id):
        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 _notify_observers(self) -> None:
        for observer in self._observers:
            observer.on_elevator_moved(self.id, self.current_floor, self.direction)

    def move(self, strategy):
        # ... movement logic ...
        self._notify_observers()  # All observers update automatically

# Adding a new observer type — ZERO changes to Elevator:
class MonitoringDashboard(ElevatorObserver):
    def on_elevator_moved(self, elevator_id, floor, direction):
        print(f"[monitor] elevator {elevator_id}: floor {floor}, {direction.value}")  # log to the monitoring system

Why Observer and Not Alternatives

Why not polling? Floor displays could poll each elevator every second for its position. This wastes resources when elevators are idle and introduces latency — displays update on the poll interval, not instantly. Observer gives real-time push updates.

Why not Event Bus / Mediator? For a system with 2-4 elevators and 10-50 floors, a global event bus adds unnecessary indirection. The direct observer registration is simpler and more debuggable. If the system scaled to 100+ elevators with dozens of observer types, an event bus would be appropriate.

Why not direct method calls? This is what we showed in the "bad" example — it creates tight coupling between Elevator and every observer type. Observer inverts the dependency: the elevator depends only on the ElevatorObserver interface, and whoever builds the system — ElevatorSystem.__init__() — registers the displays.

Patterns Working Together

These three patterns collaborate seamlessly in the main simulation loop:

  1. Strategy decides WHERE the elevator should go → strategy.get_next_stop(elevator)
  2. State governs HOW the elevator transitions → elevator.move() closes the doors and sets MOVING_UP or MOVING_DOWN as it leaves; stop() sets DOOR_OPEN
  3. Observer broadcasts WHAT happened → elevator._notify_observers() after each move

This separation means:

  • Changing the scheduling algorithm doesn't affect state management or display updates
  • Adding a new state (e.g., EMERGENCY) stays inside Elevator and ElevatorState — except where the strategies' select_elevator() reads the state: a car that can't take calls must be skipped there
  • Adding new display types doesn't affect scheduling or state management

Each pattern isolates one dimension of change, following the Single Responsibility Principle (Fundamentals S12).

Sequence diagram of how Strategy, State and Observer work together, as the code runs it: a hall call — add_hall_call(7, DOWN), dispatch(request), select_elevator(request, elevators) on the strategy returning car 1, add_request(request); one step — step(), move(strategy), get_next_stop(self) on the strategy returning 7, close() on the Door, state = MOVING_UP and current_floor += 1 (IDLE → MOVING_UP); the same move() — _notify_observers() and, for each of the ten floor displays, on_elevator_moved(1, 2, UP), then should_stop(2), False; at floor 7, five steps on, should_stop is true: stop() calls open() on the Door (MOVING_UP → DOOR_OPEN) and, its last request served, close() again → IDLE

Interview Tips

When discussing patterns in an interview:

DON'T just name-drop patterns. Saying "I'd use Strategy here" isn't enough.

DO explain the decision process:

  1. Identify the variation — "We have three scheduling algorithms that need to be swappable."
  2. Name the pattern — "The Strategy Pattern handles this."
  3. Justify over alternatives — "Template Method would work but prevents runtime switching. Simple if/else violates Open/Closed."
  4. Show awareness of trade-offs — "Full State classes are overkill for 4 states but would be warranted for 8+."

Also know when NOT to use a pattern. Over-applying patterns is a common mistake. If there's only one scheduling algorithm and no plan for more, Strategy adds unnecessary abstraction.