Design Patterns Applied
Patterns Overview
Our Parking Lot system uses two design patterns and one design principle that profoundly shape its structure:
- Strategy Pattern — for pluggable pricing algorithms (Behavioral, Fundamentals S12)
- Factory Method Pattern — for creating vehicles by type (Creational, Fundamentals S10)
- Single Responsibility Principle — pervasive throughout the design (Fundamentals S6)
For each pattern, we'll examine:
- What problem does it solve in this specific design?
- How is it applied — which classes are involved?
- Why this pattern and not alternatives?
- What would happen without it — the "before" comparison
This is an Easy-level problem, so we use a small number of well-chosen patterns. As problems get harder (DP8 Elevator, DP21 Chess), you'll see 3-4 patterns interacting together.
Strategy Pattern — Pluggable Pricing
Category: Behavioral Pattern (Fundamentals S12 — Strategy Pattern — Swappable Algorithms)
The Problem It Solves
The parking lot needs to support multiple pricing models: hourly pricing (charge per hour), flat-rate pricing (fixed fee), and potentially future models like dynamic surge pricing, weekend pricing, or tiered pricing. Without a pattern, the fee calculation logic would live inside ParkingLot as a conditional:
if pricing_type == "hourly":
fee = hours * hourly_rate
elif pricing_type == "flat_rate":
fee = flat_rate
elif pricing_type == "surge":
fee = hours * base_rate * surge_multiplierEvery new pricing model requires modifying the ParkingLot class — violating the Open/Closed Principle (Fundamentals S6). The class grows, testing becomes harder, and unrelated pricing logic is tangled together.
How We Applied It
We defined a PricingStrategy interface with a single method calculateFee(duration). Each pricing model is a separate class implementing this interface:
HourlyPricing— calculatesceil(hours) × hourlyRateFlatRatePricing— returns a fixed rate regardless of duration
The ParkingLot holds a reference to PricingStrategy (not to a concrete implementation). It calls pricingStrategy.calculateFee(duration) without knowing which algorithm runs. The strategy can be swapped at runtime via setPricingStrategy().
Why Strategy and Not Alternatives?
Why not if/else (Conditional)?
Conditionals violate OCP — every new pricing model changes ParkingLot. With Strategy, adding WeekendPricing means creating one new class. Zero changes to existing code.
Why not Template Method?
Template Method is for algorithms that share a fixed sequence of steps with varying implementations. Our pricing models don't share a common step sequence — hourly pricing and flat-rate pricing are fundamentally different algorithms. Strategy is for interchangeable, independent algorithms.
Why not Decorator?
Decorator wraps an existing strategy to add behavior (e.g., "add a surcharge to hourly pricing"). If we needed composable pricing layers (base + surcharge + tax), Decorator would complement Strategy. For our Easy-level scope, plain Strategy is sufficient.
The "Before" — Without Strategy
Here's what unparkVehicle looks like WITHOUT the pattern:
# ❌ WITHOUT Strategy Pattern — violates OCP
class ParkingLot:
def __init__(self, name: str, pricing_type: str, rate: float):
self.pricing_type = pricing_type
self.rate = rate
def unpark_vehicle(self, ticket_id: str) -> float:
ticket = self.active_tickets.pop(ticket_id)
hours = calculate_hours(ticket.entry_time)
# Every new pricing model adds another branch HERE
if self.pricing_type == "hourly":
fee = math.ceil(hours) * self.rate
elif self.pricing_type == "flat_rate":
fee = self.rate
elif self.pricing_type == "surge": # Added later — modifies ParkingLot!
fee = math.ceil(hours) * self.rate * self.surge_multiplier
# ... grows forever
ticket.spot.unpark()
return feeCompare with our implementation:
# ✅ WITH Strategy Pattern — OCP compliant
def unpark_vehicle(self, ticket_id: str) -> float:
ticket = self.active_tickets.pop(ticket_id)
duration = datetime.now() - ticket.entry_time
fee = self.pricing_strategy.calculate_fee(duration) # One line. Never changes.
ticket.spot.unpark()
return feeThe ParkingLot.unpark_vehicle() method is closed for modification — it will never change regardless of how many pricing models we add. But the system is open for extension — just create a new class implementing PricingStrategy.
Factory Method — Vehicle Creation
Category: Creational Pattern (Fundamentals S10 — Factory Pattern — Delegated Object Creation)
The Problem It Solves
In our current implementation, the client code directly creates vehicles:
car = Car("ABC-1234")
truck = Truck("TRK-5678")This works fine for our current scope, but imagine the parking lot receives vehicles from an external system (a license plate scanner, for example) that sends {type: "CAR", plate: "ABC-1234"}. The client code would need to write:
if data["type"] == "CAR":
vehicle = Car(data["plate"])
elif data["type"] == "TRUCK":
vehicle = Truck(data["plate"])
elif data["type"] == "MOTORCYCLE":
vehicle = Motorcycle(data["plate"])This conditional is repeated everywhere a vehicle is created. Adding a new vehicle type (e.g., ElectricVehicle) requires finding and updating every creation point.
How We'd Apply It
A VehicleFactory centralizes creation logic:
class VehicleFactory:
"""Factory Method — centralizes vehicle creation logic."""
@staticmethod
def create_vehicle(vehicle_type: VehicleType, license_plate: str) -> Vehicle:
creators = {
VehicleType.CAR: Car,
VehicleType.TRUCK: Truck,
VehicleType.MOTORCYCLE: Motorcycle,
}
creator = creators.get(vehicle_type)
if creator is None:
raise ValueError(f"Unknown vehicle type: {vehicle_type}")
return creator(license_plate)
# Usage — clean, extensible
vehicle = VehicleFactory.create_vehicle(VehicleType.CAR, "ABC-1234")public class VehicleFactory {
public static Vehicle createVehicle(VehicleType type, String licensePlate) {
return switch (type) {
case CAR -> new Car(licensePlate);
case TRUCK -> new Truck(licensePlate);
case MOTORCYCLE -> new Motorcycle(licensePlate);
};
}
}Why Factory and Not Alternatives?
Why not Abstract Factory?
Abstract Factory creates families of related objects (e.g., a Windows UI factory that creates WindowsButton + WindowsScrollbar). Our vehicles aren't a "family" — they're independent types. Simple Factory Method is sufficient.
Why not Builder?
Builder is for objects with many optional parameters and complex construction. Our vehicles have just one parameter (licensePlate). A Builder would be over-engineering.
Note: The Factory is optional for our Easy-level scope since direct construction works fine in the sample code. But in a real system receiving data from external sources, centralizing creation logic becomes essential. This is why we mention it — to prepare you for Medium and Hard problems where Factory is mandatory (like DP20 Online Shopping, where ProductFactory creates different product types from database records).
Single Responsibility Principle — Class Focus
Category: Design Principle (Fundamentals S6 — S — Single Responsibility Principle)
SRP isn't a design pattern in the GoF sense, but it is the most impactful structural decision in our Parking Lot design. Every class has exactly one reason to change:
| Class | Responsibility | Reason to Change |
|---|---|---|
ParkingLot | Coordinate parking operations | Workflow changes (e.g., add reservation step) |
Floor | Manage spot collection on one floor | Floor-level logic changes (e.g., spot search order) |
ParkingSpot | Track occupancy and compatibility | Compatibility rules change (e.g., new spot type) |
Vehicle / subclasses | Model vehicle identity and type | Vehicle attributes change (e.g., add color) |
PricingStrategy impls | Calculate fees | Pricing algorithm changes |
ParkingTicket | Record a parking session | Session data changes (e.g., add exit time field) |
What would happen without SRP?
Imagine a single ParkingSystem class that handles spot allocation, fee calculation, ticket management, compatibility checking, and capacity tracking — like the OrderProcessor anti-pattern from Fundamentals S6. Changing the pricing algorithm risks breaking spot allocation. Adding a new vehicle type requires touching the same class that manages tickets. Every change is high-risk.
With SRP, each class is a blade — sharp, focused, and replaceable without affecting the others. This is what makes the design extensible and testable.
Pattern Interaction Map
Our patterns don't work in isolation — they reinforce each other:
-
Strategy + SRP → The pricing algorithm is extracted from ParkingLot into its own class hierarchy. SRP tells us that the pricing logic should be separate. Strategy tells us how to separate it (via an interface with swappable implementations).
-
Factory + SRP → Vehicle creation is extracted from the client code into a dedicated factory. Even if we don't use a formal Factory class in our Easy-level code, the principle of separating creation from usage is visible — each Vehicle subclass constructor encapsulates its own type assignment.
-
Strategy + OCP → The Strategy Pattern is the mechanism for achieving the Open/Closed Principle. Without a pattern, OCP is a principle without an implementation. Strategy provides the concrete structure: interface + implementations + runtime injection.
Cross-reference to other design problems:
- The Elevator System (DP8) also uses Strategy — for scheduling algorithms (FCFS, SCAN, LOOK) instead of pricing.
- The Vending Machine (DP6) uses the State Pattern instead of Strategy — because Vending Machine behavior changes based on state, not algorithm choice. Strategy and State have similar structures but solve different problems.
- The Car Rental System (DP12) uses both Strategy (pricing) AND Factory (vehicle types) — a more complex version of our patterns.
As you progress through the course, you'll see these same patterns applied to increasingly complex domains. The Parking Lot is your foundation — the first time you see Strategy and Factory in action in a real design.