Bird
Raised Fist0
LLDsystem_design~7 mins

Parking strategy pattern in LLD - System Design Guide

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Problem Statement
When a parking system needs to support multiple ways to park cars, hardcoding all parking rules in one place makes the code complex and hard to change. Adding new parking strategies or changing existing ones requires modifying core logic, risking bugs and slowing development.
Solution
The parking strategy pattern separates different parking algorithms into independent classes. The system selects and uses a parking strategy at runtime without changing the main parking logic. This makes it easy to add, remove, or modify parking methods without touching the core system.
Architecture
ParkingSystem
ParkingStrategy (I)
FirstAvailable
Strategy

This diagram shows the ParkingSystem using a ParkingStrategy interface. Different concrete strategies like FirstAvailable, NearestEntrance, and RandomParking implement this interface. The system delegates parking decisions to the chosen strategy.

Trade-offs
✓ Pros
Allows adding new parking strategies without changing existing code.
Improves code maintainability by separating concerns.
Enables runtime selection of parking algorithms for flexibility.
Facilitates testing individual strategies independently.
✗ Cons
Increases number of classes and interfaces, adding structural complexity.
Requires careful design to keep strategy interface consistent.
May introduce slight runtime overhead due to delegation.
Use when the parking system must support multiple parking algorithms or rules that may change or grow over time, especially if the system handles more than 1000 parking requests per hour requiring flexible decision logic.
Avoid when the parking logic is simple and unlikely to change, such as a small parking lot with a single fixed parking rule, where added abstraction would be unnecessary overhead.
Real World Examples
Uber
Uber uses strategy patterns to decide how to assign drivers to riders based on different algorithms like nearest driver, driver rating, or surge pricing zones.
Amazon
Amazon applies strategy patterns in warehouse robot parking and task assignment, switching strategies based on load and robot availability.
LinkedIn
LinkedIn uses strategy patterns for resource allocation in data centers, choosing different strategies based on workload types and priorities.
Code Example
The before code mixes all parking logic inside one method using conditionals, making it hard to extend. The after code defines a ParkingStrategy interface and separate classes for each strategy. ParkingSystem uses a strategy instance to delegate parking decisions, enabling easy swapping and extension.
LLD
### Before: Without Strategy Pattern
class ParkingSystem:
    def park_car(self, car, strategy):
        if strategy == 'first_available':
            # find first available spot
            pass
        elif strategy == 'nearest_entrance':
            # find spot nearest to entrance
            pass
        else:
            # default parking
            pass

### After: With Strategy Pattern
from abc import ABC, abstractmethod

class ParkingStrategy(ABC):
    @abstractmethod
    def find_spot(self, parking_lot, car):
        pass

class FirstAvailableStrategy(ParkingStrategy):
    def find_spot(self, parking_lot, car):
        # logic to find first available spot
        return 'Spot1'

class NearestEntranceStrategy(ParkingStrategy):
    def find_spot(self, parking_lot, car):
        # logic to find spot nearest entrance
        return 'Spot2'

class ParkingSystem:
    def __init__(self, strategy: ParkingStrategy):
        self.strategy = strategy

    def park_car(self, car):
        spot = self.strategy.find_spot(None, car)
        print(f'Parking car at {spot}')

# Usage
system = ParkingSystem(FirstAvailableStrategy())
system.park_car('CarA')

system.strategy = NearestEntranceStrategy()
system.park_car('CarB')
OutputSuccess
Alternatives
Conditional Statements
Implements all parking logic in one place using if-else or switch-case blocks.
Use when: When the number of parking strategies is very small and unlikely to change.
Template Method
Defines a skeleton of parking algorithm in a base class with some steps overridden by subclasses.
Use when: When parking strategies share a common sequence of steps with minor variations.
Summary
The parking strategy pattern prevents complex, hard-to-change parking logic by separating algorithms into independent classes.
It allows the system to select and switch parking methods at runtime without modifying core code.
This pattern improves maintainability and flexibility, especially when multiple parking rules must coexist or evolve.

Practice

(1/5)
1. What is the main purpose of using the Parking Strategy Pattern in a parking lot system?
easy
A. To store vehicle details in a database
B. To manage payment processing for parking fees
C. To allow different algorithms for finding parking spots without changing the main system
D. To control the physical gates of the parking lot

Solution

  1. Step 1: Understand the role of strategy pattern

    The strategy pattern lets you swap different algorithms easily without changing the main code.
  2. Step 2: Apply this to parking system context

    In parking, it means you can change how spots are found without rewriting the whole system.
  3. Final Answer:

    To allow different algorithms for finding parking spots without changing the main system -> Option C
  4. Quick Check:

    Strategy pattern = flexible parking spot finding [OK]
Hint: Strategy pattern = flexible algorithm swapping [OK]
Common Mistakes:
  • Confusing strategy pattern with data storage
  • Thinking it controls hardware like gates
  • Mixing it with payment processing logic
2. Which of the following is the correct way to define a parking strategy interface in a typical object-oriented design?
easy
A. class ParkingStrategy { findSpot(vehicle) {} }
B. function findSpot(vehicle) { return spot; }
C. var ParkingStrategy = new Object();
D. interface ParkingStrategy { findSpot(vehicle): Spot; }

Solution

  1. Step 1: Identify interface syntax in OOP

    Interfaces define method signatures without implementation, e.g., interface ParkingStrategy { findSpot(vehicle): Spot; }.
  2. Step 2: Compare options

    interface ParkingStrategy { findSpot(vehicle): Spot; } correctly uses interface with method signature. Others are class, function, or object, not interface.
  3. Final Answer:

    interface ParkingStrategy { findSpot(vehicle): Spot; } -> Option D
  4. Quick Check:

    Interface = method signature only [OK]
Hint: Interface defines method signatures only [OK]
Common Mistakes:
  • Using class instead of interface for strategy
  • Defining functions outside interface context
  • Confusing object creation with interface definition
3. Given the following code snippet for two parking strategies, what will be the output when findSpot(vehicle) is called using NearestParkingStrategy?
class NearestParkingStrategy {
  findSpot(vehicle) {
    return "Nearest spot found";
  }
}
class RandomParkingStrategy {
  findSpot(vehicle) {
    return "Random spot found";
  }
}
const strategy = new NearestParkingStrategy();
console.log(strategy.findSpot('car'));
medium
A. "Nearest spot found"
B. "Random spot found"
C. undefined
D. Error: findSpot not defined

Solution

  1. Step 1: Identify which strategy instance is used

    The code creates an instance of NearestParkingStrategy and calls findSpot.
  2. Step 2: Check method output for that class

    NearestParkingStrategy.findSpot returns "Nearest spot found".
  3. Final Answer:

    "Nearest spot found" -> Option A
  4. Quick Check:

    Instance method output = "Nearest spot found" [OK]
Hint: Instance method output matches class used [OK]
Common Mistakes:
  • Confusing which strategy instance is created
  • Assuming random strategy is used
  • Expecting undefined or error without reason
4. In the following code, what is the main issue that prevents the ParkingLot from using different parking strategies correctly?
class ParkingLot {
  constructor() {
    this.strategy = null;
  }
  setStrategy(strategy) {
    this.strategy = strategy;
  }
  park(vehicle) {
    return this.strategy.findSpot(vehicle);
  }
}
const lot = new ParkingLot();
lot.park('car');
medium
A. No strategy is set before calling park, causing an error
B. The park method should not call findSpot
C. The strategy property should be a list, not a single object
D. The constructor should initialize strategy with a default value

Solution

  1. Step 1: Analyze object initialization and method calls

    The ParkingLot is created with strategy = null. No strategy is set before calling park.
  2. Step 2: Understand consequence of null strategy

    Calling this.strategy.findSpot(vehicle) when strategy is null causes an error.
  3. Final Answer:

    No strategy is set before calling park, causing an error -> Option A
  4. Quick Check:

    Null strategy causes error on method call [OK]
Hint: Always set strategy before use [OK]
Common Mistakes:
  • Thinking park method logic is wrong
  • Assuming strategy should be a list
  • Ignoring null initialization problem
5. You want to design a parking system that supports multiple vehicle types (car, bike, truck) and different parking strategies (nearest, random, reserved). Which design approach best uses the Parking Strategy Pattern to handle this complexity?
hard
A. Create separate parking lot classes for each vehicle type and hardcode the strategy inside each
B. Use a single ParkingLot class with a strategy interface; implement different strategies and select based on vehicle type at runtime
C. Store all vehicles in one list and assign spots randomly without strategy pattern
D. Use global variables to track vehicle types and apply strategies in procedural code

Solution

  1. Step 1: Identify need for flexibility and scalability

    Supporting multiple vehicle types and strategies requires flexible design without code duplication.
  2. Step 2: Apply strategy pattern with runtime selection

    Using one ParkingLot class with strategy interface allows swapping strategies dynamically based on vehicle type.
  3. Step 3: Evaluate other options

    Create separate parking lot classes for each vehicle type and hardcode the strategy inside each duplicates code, C ignores strategy pattern, D uses poor global state management.
  4. Final Answer:

    Use a single ParkingLot class with a strategy interface; implement different strategies and select based on vehicle type at runtime -> Option B
  5. Quick Check:

    Strategy pattern + runtime selection = best design [OK]
Hint: Use one class + strategy interface + runtime choice [OK]
Common Mistakes:
  • Duplicating classes per vehicle type
  • Ignoring strategy pattern benefits
  • Using global variables instead of OOP