Strategy Pattern
Many classes do one job that can be done in several ways. A ride can be priced as economy, premium or pool. A parking lot can fill the spot nearest the entrance or fill one level at a time. A cache can evict the least recently used item or the least frequently used one. The job stays the same; only the way of doing it changes.
The Strategy pattern gives each way its own class behind one shared interface, and lets the main class hold whichever one it needs. It is the pattern you will use most often in low-level design interviews, because almost every prompt has at least one "it can be done several ways" rule.
π§© In one sentence: put each interchangeable algorithm in its own class behind a common interface, and have the class that uses it hold a reference to one, so you can add or swap algorithms without editing that class.
The Problem It Solves
Here is a fare calculator for a ride-sharing app, written the way it usually starts: one method, one branch per ride type.
class FareCalculator:
def fare(self, ride_type: str, km: float, minutes: float, riders: int, surge: float) -> int:
if ride_type == "economy":
cents = 200 + 90 * km + 20 * minutes
elif ride_type == "premium":
cents = max(1_500, 500 + 180 * km + 40 * minutes) # minimum fare
elif ride_type == "pool":
base = 200 + 90 * km + 20 * minutes
cents = base * (0.75 if riders > 1 else 0.9) # cheaper when shared
elif ride_type == "airport":
cents = 4_500 # flat rate, no surge
return cents
else:
raise ValueError(f"unknown ride type {ride_type}")
return round(cents * surge)
It works, and for two ride types it would be fine. The trouble starts as the business grows.
Every new type edits the same method. Adding "XL" means opening fare, adding a branch, and re-testing all
the others, because they share local variables and an early return that is easy to miss (look at airport).
This is the open/closed principle being broken: working code changes every time a feature is added.
The parameters are the union of every branch's needs. riders only matters for pool, and surge is ignored
for airport rides. Callers must pass everything, and nothing tells them which arguments matter.
The switch spreads. Ride type also decides which cars can be matched, what the receipt says and whether
tolls are added. Each of those places grows its own if ride_type == ... chain, and adding a type means finding
all of them. Miss one and you get a pool ride with a premium receipt.
It is hard to test one rule. To test the premium minimum fare, you call a method that also contains three
other pricing rules, and a typo like "premim" only fails at runtime.
β οΈ The smell to look for: an
if/eliforswitchon a type field, where each branch does a different calculation, and the same field is switched on in more than one place. That is the cue for Strategy.
How It Works
The pattern has three participants and one decision.
- Strategy: the interface for the job. One method, here
fare(trip) -> int. - Concrete strategies: one class per way of doing the job. Each holds only the rules for its case.
- Context: the class that needs the job done. It holds a strategy and delegates to it, without knowing which one it has.
- Who chooses: some code picks the strategy and hands it to the context, usually at construction time. The
if/elifon type doesn't vanish; it shrinks to one place that runs once.
Here is the fare calculator refactored. Each branch became a class, and the inputs travel as one Trip value
instead of a growing list of parameters.
@dataclass(frozen=True)
class Trip:
km: float
minutes: float
riders: int = 1
surge: float = 1.0
class PricingStrategy(ABC):
@abstractmethod
def fare(self, trip: Trip) -> int: ...
class EconomyPricing(PricingStrategy):
def fare(self, trip: Trip) -> int:
return round((200 + 90 * trip.km + 20 * trip.minutes) * trip.surge)
class PremiumPricing(PricingStrategy):
def fare(self, trip: Trip) -> int:
return round(max(1_500, 500 + 180 * trip.km + 40 * trip.minutes) * trip.surge)
class PoolPricing(PricingStrategy):
def fare(self, trip: Trip) -> int:
share = 0.75 if trip.riders > 1 else 0.9
return round(EconomyPricing().fare(trip) * share)
class AirportFlatRate(PricingStrategy):
def fare(self, trip: Trip) -> int:
return 4_500
The context is now tiny. Ride doesn't know there are four pricing rules; it only knows it has one.
class Ride:
def __init__(self, rider_id: str, pricing: PricingStrategy) -> None:
self.rider_id = rider_id
self.pricing = pricing
def complete(self, trip: Trip) -> int:
return self.pricing.fare(trip)
And the one remaining choice lives in a lookup table, not in business logic:
PRICING: dict[str, PricingStrategy] = {
"economy": EconomyPricing(),
"premium": PremiumPricing(),
"pool": PoolPricing(),
"airport": AirportFlatRate(),
}
ride = Ride("rider-42", PRICING["premium"])
ride.complete(Trip(km=3, minutes=10)) # 1500: the minimum fare applies
Compare this with the original against each problem listed above. Adding "XL" is one new class and one new
dictionary entry; Ride and the other strategies don't change. Each class takes only what it uses. Testing the
premium minimum is assert PremiumPricing().fare(Trip(1, 2)) == 1_500. And if receipts also vary by type, you add
a receipt_label() method to the same interface, so one class per type keeps every type-specific rule together.
A Worked Example
Here is how Strategy shows up in a real interview problem, from requirement to running code.
The requirement. You are designing a parking lot with several levels. Partway through, your interviewer adds: "The operator wants to choose how spots are assigned. The default is the free spot nearest the entrance. At night they want to fill one level completely before opening the next, so they can close the upper levels."
Spotting the pattern. There is one job (pick a spot for a vehicle), two ways of doing it, the choice changes at runtime, and more rules are plausible ("reserve the ground floor for electric cars"). That is Strategy.
The interface. The strategy needs the levels and the vehicle, and returns a spot or nothing.
class SpotSelector(ABC):
@abstractmethod
def select(self, levels: list[Level], vehicle: Vehicle) -> Spot | None: ...
Two strategies. Each one is a few lines and contains only its own rule.
class NearestToEntrance(SpotSelector):
def select(self, levels: list[Level], vehicle: Vehicle) -> Spot | None:
free = [s for lvl in levels for s in lvl.spots if s.is_free() and s.fits(vehicle)]
return min(free, key=lambda s: s.distance_to_entrance, default=None)
class FillLevelByLevel(SpotSelector):
def select(self, levels: list[Level], vehicle: Vehicle) -> Spot | None:
for level in sorted(levels, key=lambda l: l.number):
for spot in level.spots:
if spot.is_free() and spot.fits(vehicle):
return spot
return None
The context. ParkingLot owns the levels and the ticketing rules. It asks its selector for a spot and does
everything else itself. set_selector lets the operator switch rules without restarting anything.
class ParkingLot:
def __init__(self, levels: list[Level], selector: SpotSelector) -> None:
self.levels = levels
self.selector = selector
def set_selector(self, selector: SpotSelector) -> None:
self.selector = selector
def park(self, vehicle: Vehicle) -> Ticket | None:
spot = self.selector.select(self.levels, vehicle)
if spot is None:
return None # lot is full for this vehicle size
spot.assign(vehicle)
return Ticket(vehicle.plate, spot.id)
Tracing it. A lot has two levels, all spots free. Level 1 has 1A (distance 40) and 1B (distance 45);
level 2 has 2A (distance 10) and 2B (distance 15), right next to the elevator.
lot = ParkingLot(levels, NearestToEntrance()).lot.park(car1)returns a ticket for2A, the closest spot.- At 10 p.m. the operator calls
lot.set_selector(FillLevelByLevel()). Free spots:1A,1B,2B. lot.park(car2)returns a ticket for1A, the first free spot on the lowest level. The old rule would have picked2B.- Nothing in
park,TicketorLevelchanged between steps 1 and 3.
The follow-up. "Electric cars should go to charging spots first." You add ChargingFirst(SpotSelector),
which looks for a free charging spot and falls back to another selector you pass in. ParkingLot is untouched,
which is exactly the answer your interviewer is looking for.
Variations
Functions as strategies. When a strategy has one method and no state, a plain function is enough. In Python, the interface is just a type alias for a callable:
FareRule = Callable[[Trip], int]
def economy(trip: Trip) -> int:
return round((200 + 90 * trip.km + 20 * trip.minutes) * trip.surge)
ride = Ride("rider-42", pricing=economy) # Ride calls self.pricing(trip)
Java does the same with a functional interface, so a lambda can stand in for a class:
@FunctionalInterface
interface PricingStrategy {
long fare(Trip trip);
}
PricingStrategy airport = trip -> 4_500;
PricingStrategy economy = trip -> Math.round((200 + 90 * trip.km() + 20 * trip.minutes()) * trip.surge());
In an interview, start with classes if the strategies might grow a second method or need configuration; otherwise functions are lighter and just as clear.
Configured strategies. A strategy can take constructor arguments, so one class covers a family of rules:
PercentOff(10) and PercentOff(25) are two discounts from one class. This keeps the class count down when the
variants differ only in numbers.
Stateful strategies. Some strategies remember things. A round-robin selector for assigning support tickets to
agents keeps a counter. A stateless strategy can be shared by every context (one EconomyPricing() instance for
all rides); a stateful one needs its own instance per context, and a lock if several threads use it.
Combining strategies. Sometimes several strategies apply at once, such as stacking discounts on a cart. Keep each discount a strategy, and let the context hold a list and decide how to combine them (add them all, or apply only the best one). The combining rule can itself be a strategy if it varies.
When Not to Use It
Strategy adds an interface and a class per case. That is a good trade only when the cases really differ in behavior and are likely to grow.
- The cases differ only in data. If economy, premium and XL all use
base + per_km * km + per_min * minuteswith different numbers, you don't need four classes. Use one class and a table of rates:RATES = {"economy": (200, 90, 20), "premium": (500, 180, 40)}. Strategy is for different logic, not different constants. - There are two cases and there will only ever be two. A light switch is on or off. An
ifis clearer than an interface with two implementations. - The behavior depends on the object's own state and changes as it moves. A vending machine behaves differently when idle, holding money or dispensing, and it moves between those modes by itself. That is the State pattern (see below), not Strategy.
- Nothing will ever swap it. If the prompt has one pricing rule and no hint of more, write the rule inline and say you would extract a strategy when a second rule arrives. That is YAGNI, and saying it out loud shows judgment.
π‘ Interview tip: before you introduce a strategy, say what varies and why it will grow: "Pricing differs per ride type, and the prompt says new types are coming, so I'll put pricing behind an interface." One sentence makes the pattern a decision rather than a reflex.
In LLD Interviews
Strategy appears somewhere in most problem breakdowns. These are the places you will meet it most often:
| Problem | What varies (the strategy) |
|---|---|
| Parking Lot | fee rules per vehicle type, spot selection |
| Ride-Sharing | fare calculation, driver matching |
| Shopping Cart | discount and coupon rules |
| LRU Cache | eviction policy (LRU, LFU) |
| Rate Limiter | algorithm (token bucket, sliding window) |
| Elevator | which elevator answers a call |
| Splitwise | equal, exact and percent splits |
| Payment System | which provider handles a payment method |
| Lead Distribution | round robin, least loaded, skills-based assignment |
How to bring it up. Listen for prompts that list alternatives for one behavior: "fees depend on...", "it can use X or Y", "the operator chooses...". Name the job, propose the interface with its one method, write one or two concrete strategies fully, and list the rest by name. Then show where the choice is made (constructor argument or a lookup table). When the inevitable "how would you add another type?" follow-up comes, the answer is already on the board: one new class, no edits to the context.
Related Patterns
Several patterns look like Strategy on a class diagram. The difference is in who decides and why.
- State: also an interface with swappable implementations held by a context. But in State, the states
switch the context themselves as events happen (a vending machine goes from
IdletoHasMoney), and the client usually doesn't know which state is active. In Strategy, the client picks the algorithm and the strategies don't know about each other. See the State Pattern. - Template Method: varies steps of an algorithm through inheritance: a base class fixes the order and subclasses override steps. Strategy varies the whole algorithm through composition, so it can be swapped at runtime. See the Template Method Pattern.
- Factory: often sits next to Strategy. The factory decides which strategy to create from a config value or a type name; the strategy does the work. The lookup table above is a minimal factory. See the Factory Pattern.
- Command: also wraps behavior in an object, but a command represents a request to run later, undo or queue ("move this piece"). A strategy represents a way of doing a job the context runs now.
- Decorator: wraps an object to add behavior on top of it (logging, caching) while keeping the same interface. Strategy replaces the behavior instead of layering on it.
Summary
- Strategy puts each interchangeable algorithm in its own class behind one interface; the context holds one and delegates to it.
- It replaces
if/elifchains on a type where each branch does a different calculation, especially when the same type is switched on in several places. - New behavior means a new class, with no edits to the context: the open/closed principle in practice.
- The choice of strategy moves to one place, usually a constructor argument or a lookup table, and can change at runtime.
- Use plain functions when a strategy has one method and no state; use one configured class when variants differ only in numbers.
- Skip it when cases differ only in data, when there are two fixed cases, or when the object changes its own behavior as its state changes (that's State).