Design Patterns Applied
Patterns Overview
Our Elevator System uses three design patterns, each solving a distinct problem:
| Pattern | Problem Solved | Applied To |
|---|---|---|
| Strategy | Multiple scheduling algorithms that must be interchangeable at runtime | SchedulingStrategy → FCFSStrategy, SCANStrategy, LOOKStrategy |
| State | Elevator behavior changes dramatically based on its current state | ElevatorState enum driving transitions in Elevator.move() |
| Observer | Floor displays must update automatically when elevators move | ElevatorObserver → 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:
Dispatcherholds a reference toSchedulingStrategy; each step,ElevatorSystemhands the same strategy to everyElevator.move() - Strategy interface:
SchedulingStrategywithselect_elevator()andget_next_stop() - Concrete strategies:
FCFSStrategy,SCANStrategy,LOOKStrategy
Switching is one line: dispatcher.set_strategy(LOOKStrategy())

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 methodHow We Applied It
We use state-driven behavior through the ElevatorState enum and structured transitions in the move() method:
- State represented by enum:
ElevatorState.IDLE,MOVING_UP,MOVING_DOWN,DOOR_OPEN - Transitions in one place:
move()decides from the next stop — it closes the doors and setsMOVING_UPorMOVING_DOWNas the car leaves a floor,stop()setsDOOR_OPENat a requested floor, and with nothing left the car goesIDLE - Guard conditions: The door must be closed before movement; the elevator must have requests to move
- Clean transition logic:
stateanddirectionchange 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().

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:
Elevatormaintains a list ofElevatorObserverreferences - Observer interface:
ElevatorObserverwithon_elevator_moved(elevator_id, floor, direction) - Concrete observer:
FloorDisplayimplementsElevatorObserver - 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 systemWhy 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:
- Strategy decides WHERE the elevator should go →
strategy.get_next_stop(elevator) - State governs HOW the elevator transitions →
elevator.move()closes the doors and setsMOVING_UPorMOVING_DOWNas it leaves;stop()setsDOOR_OPEN - 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
ElevatorandElevatorState— 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).

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:
- Identify the variation — "We have three scheduling algorithms that need to be swappable."
- Name the pattern — "The Strategy Pattern handles this."
- Justify over alternatives — "Template Method would work but prevents runtime switching. Simple if/else violates Open/Closed."
- 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.