Strategy Pattern
Strategy is the pattern you'll reach for most often in LLD interviews, and the one interviewers most expect you to justify rather than just name. Pricing rules, payment methods, parking-fee calculators, elevator scheduling, ranking algorithms and retry policies are all strategies in disguise. This page goes deeper than the short section in the behavioral patterns overview: it builds a checkout with pricing and payment strategies in Java, Python and TypeScript, shows when a plain function replaces a whole class hierarchy, and covers the questions that come up once the basic shape is on the whiteboard. Who picks the strategy? Where does its data come from? When is a switch actually fine?
Intent
Define a family of interchangeable algorithms behind one interface, so the code that uses an algorithm doesn't change when you add, remove or swap one.
Three ideas are packed into that sentence:
- A family. The variants all answer the same question: "what does this cart cost?", "how do we collect this money?", "which elevator goes next?". If the variants answer different questions, they aren't a family, and forcing them behind one interface produces a leaky abstraction.
- Interchangeable. Any variant can stand in for any other without the caller noticing. That is the Liskov substitution promise applied to algorithms.
- The caller doesn't change. New behaviour arrives as a new class or function, not as another branch in existing code. That is the open-closed principle in its most practical form.
The object that uses a strategy is called the context. The context owns the workflow (validate the cart, compute the total, take the payment, issue a receipt) and delegates one step of it to whatever strategy it was given.
The problem
Imagine an online shop's checkout. It started with one price and one way to pay. Then marketing added member discounts. Then a seasonal tiered sale. Then the payments team added UPI and an in-app wallet. Every request landed in the same method:
import java.util.List;
record Item(String sku, long unitCents, int qty) {}
class CheckoutService {
// customerType: "regular", "member", "seasonal"
// paymentMethod: "card", "upi", "wallet"
String checkout(List<Item> items, String customerType, String paymentMethod,
String cardNumber, String upiId, long[] walletBalance) {
long subtotal = 0;
for (Item i : items) subtotal += i.unitCents() * i.qty();
long total;
if (customerType.equals("member")) {
total = subtotal - subtotal * 10 / 100;
} else if (customerType.equals("seasonal")) {
if (subtotal >= 50_000) total = subtotal - subtotal * 10 / 100;
else if (subtotal >= 10_000) total = subtotal - subtotal * 5 / 100;
else total = subtotal;
} else {
total = subtotal;
}
switch (paymentMethod) {
case "card":
if (cardNumber == null || cardNumber.length() != 16) throw new IllegalArgumentException("bad card");
return "card-" + cardNumber.substring(12) + ":" + total;
case "upi":
if (upiId == null || !upiId.contains("@")) throw new IllegalArgumentException("bad upi id");
return "upi-" + upiId + ":" + total;
case "wallet":
if (walletBalance[0] < total) throw new IllegalStateException("insufficient balance");
walletBalance[0] -= total;
return "wallet:" + total;
default:
throw new IllegalArgumentException("unknown payment method " + paymentMethod);
}
}
}
It works, and for two branches it would be fine. The trouble shows up as the shop grows:
- Every new rule edits the same method. Adding "first-order 15% off" means touching code that also handles card validation. A typo in the pricing branch can break payments.
- The parameter list is a junk drawer.
cardNumber,upiIdandwalletBalanceare each meaningful for exactly one branch, yet every caller has to pass all three. Adding net banking adds a fourth. - Testing is combinatorial. Three pricing rules times three payment methods is nine paths through one method, and each test has to set up arguments it doesn't care about.
- The rules can't be reused. The mobile app wants to show the member price before checkout. The pricing logic is welded to the payment logic, so it either duplicates the
ifchain or callscheckoutand hopes nothing gets charged. - Strings select behaviour.
"memeber"compiles fine and silently falls through to full price.
Notice that there are two independent axes of variation tangled together here: how we price, and how we collect. That's a strong hint you're looking at two strategy families, not one.
Structure
classDiagram
class Checkout {
-pricing: PricingStrategy
+complete(cart, payment): Receipt
}
class PricingStrategy {
<<interface>>
+priceCents(cart): long
}
class RegularPricing {
+priceCents(cart): long
}
class PercentOffPricing {
-percent: int
+priceCents(cart): long
}
class TieredPricing {
+priceCents(cart): long
}
class PaymentStrategy {
<<interface>>
+pay(amountCents): Receipt
}
class CardPayment {
-cardNumber: String
+pay(amountCents): Receipt
}
class UpiPayment {
-vpa: String
+pay(amountCents): Receipt
}
class WalletPayment {
-balanceCents: long
+pay(amountCents): Receipt
}
Checkout --> PricingStrategy : prices with
Checkout ..> PaymentStrategy : pays with
PricingStrategy <|.. RegularPricing
PricingStrategy <|.. PercentOffPricing
PricingStrategy <|.. TieredPricing
PaymentStrategy <|.. CardPayment
PaymentStrategy <|.. UpiPayment
PaymentStrategy <|.. WalletPayment
The two arrows from Checkout are deliberately different. The pricing strategy is a field: it's chosen when the checkout is configured (per storefront, per customer plan) and lives as long as the checkout does. The payment strategy is a method parameter: the shopper picks it at the last second, and it's different on every order. Both are valid ways to hand a strategy to a context, and choosing between them is one of the design decisions an interviewer will ask you to explain.
Participants
| Participant | Role in the checkout | Responsibilities |
|---|---|---|
| Strategy (interface) | PricingStrategy, PaymentStrategy | Declares the one operation every variant must provide. Kept as small as possible, often a single method. |
| Concrete strategy | RegularPricing, PercentOffPricing, TieredPricing, CardPayment, UpiPayment, WalletPayment | Implements one algorithm. Holds whatever configuration or data that algorithm needs (a percentage, a card number, a balance). Knows nothing about the other variants. |
| Context | Checkout | Owns the workflow. Calls the strategy at the right moment and does everything that is the same regardless of the variant. Depends only on the interface. |
| Client | the storefront controller, a test, a config loader | Decides which concrete strategy the context gets. This is the only place that names concrete classes. |
The client is the participant people forget. Strategy doesn't make the decision about which algorithm to use disappear. It moves it to one place, at the edge of the system, instead of scattering it through the business logic. If your context still contains if (type == "member") new PercentOffPricing(10), you've moved the code around without gaining anything.
Implementation
All three versions below model money as integer cents (never floating point; see primitive obsession), keep strategies immutable where they can be, and end with a small demo that asserts the expected totals. The cart is two shirts at 30.00 and one cap at 50.00, so the subtotal is 110.00.
import java.util.*;
record LineItem(String sku, long unitCents, int qty) {
LineItem {
if (unitCents < 0 || qty <= 0) throw new IllegalArgumentException("bad line " + sku);
}
long totalCents() { return unitCents * qty; }
}
record Cart(List<LineItem> items) {
Cart { items = List.copyOf(items); }
long subtotalCents() { return items.stream().mapToLong(LineItem::totalCents).sum(); }
}
record Receipt(String method, long amountCents, String reference) {}
// ---------- pricing strategies ----------
@FunctionalInterface
interface PricingStrategy {
long priceCents(Cart cart);
}
final class RegularPricing implements PricingStrategy {
public long priceCents(Cart cart) { return cart.subtotalCents(); }
}
final class PercentOffPricing implements PricingStrategy {
private final int percent;
PercentOffPricing(int percent) {
if (percent < 0 || percent > 100) throw new IllegalArgumentException("percent out of range");
this.percent = percent;
}
public long priceCents(Cart cart) {
long sub = cart.subtotalCents();
return sub - sub * percent / 100;
}
}
final class TieredPricing implements PricingStrategy {
// 5% off from 100.00, 10% off from 500.00
public long priceCents(Cart cart) {
long sub = cart.subtotalCents();
int percent = sub >= 50_000 ? 10 : sub >= 10_000 ? 5 : 0;
return sub - sub * percent / 100;
}
}
// ---------- payment strategies ----------
interface PaymentStrategy {
Receipt pay(long amountCents);
}
final class CardPayment implements PaymentStrategy {
private final String cardNumber;
CardPayment(String cardNumber) {
if (cardNumber == null || !cardNumber.matches("\\d{16}")) throw new IllegalArgumentException("bad card");
this.cardNumber = cardNumber;
}
public Receipt pay(long amountCents) {
return new Receipt("card", amountCents, "card-" + cardNumber.substring(12));
}
}
final class UpiPayment implements PaymentStrategy {
private final String vpa;
UpiPayment(String vpa) {
if (vpa == null || !vpa.matches("[\\w.]+@\\w+")) throw new IllegalArgumentException("bad upi id");
this.vpa = vpa;
}
public Receipt pay(long amountCents) {
return new Receipt("upi", amountCents, "upi-" + vpa);
}
}
final class WalletPayment implements PaymentStrategy {
private long balanceCents;
WalletPayment(long balanceCents) { this.balanceCents = balanceCents; }
public Receipt pay(long amountCents) {
if (amountCents > balanceCents) throw new IllegalStateException("insufficient balance");
balanceCents -= amountCents;
return new Receipt("wallet", amountCents, "wallet-left-" + balanceCents);
}
long balanceCents() { return balanceCents; }
}
// ---------- context ----------
final class Checkout {
private final PricingStrategy pricing;
Checkout(PricingStrategy pricing) { this.pricing = Objects.requireNonNull(pricing); }
long quote(Cart cart) { return pricing.priceCents(cart); }
Receipt complete(Cart cart, PaymentStrategy payment) {
if (cart.items().isEmpty()) throw new IllegalArgumentException("empty cart");
long total = pricing.priceCents(cart);
return payment.pay(total);
}
}
// ---------- client: the one place that names concrete classes ----------
final class PricingCatalog {
private static final Map<String, PricingStrategy> BY_PLAN = Map.of(
"regular", new RegularPricing(),
"member", new PercentOffPricing(10),
"seasonal", new TieredPricing());
static PricingStrategy forPlan(String plan) {
PricingStrategy s = BY_PLAN.get(plan);
if (s == null) throw new IllegalArgumentException("unknown plan " + plan);
return s;
}
}
class Demo {
public static void main(String[] args) {
Cart cart = new Cart(List.of(new LineItem("tee", 3_000, 2), new LineItem("cap", 5_000, 1)));
assert new Checkout(PricingCatalog.forPlan("regular")).quote(cart) == 11_000;
assert new Checkout(PricingCatalog.forPlan("member")).quote(cart) == 9_900;
assert new Checkout(PricingCatalog.forPlan("seasonal")).quote(cart) == 10_450;
Checkout member = new Checkout(PricingCatalog.forPlan("member"));
Receipt upi = member.complete(cart, new UpiPayment("asha@okbank"));
assert upi.reference().equals("upi-asha@okbank") && upi.amountCents() == 9_900;
Receipt card = member.complete(cart, new CardPayment("4111111111111111"));
assert card.reference().equals("card-1111");
WalletPayment wallet = new WalletPayment(10_000);
member.complete(cart, wallet);
assert wallet.balanceCents() == 100;
try {
member.complete(cart, wallet);
assert false : "second wallet payment should fail";
} catch (IllegalStateException expected) { }
try {
PricingCatalog.forPlan("memeber");
assert false : "typo should be rejected";
} catch (IllegalArgumentException expected) { }
System.out.println("strategy demo ok");
}
}
from dataclasses import dataclass
from typing import Protocol
import re
@dataclass(frozen=True)
class LineItem:
sku: str
unit_cents: int
qty: int
def __post_init__(self) -> None:
if self.unit_cents < 0 or self.qty <= 0:
raise ValueError(f"bad line {self.sku}")
@property
def total_cents(self) -> int:
return self.unit_cents * self.qty
@dataclass(frozen=True)
class Cart:
items: tuple[LineItem, ...]
@property
def subtotal_cents(self) -> int:
return sum(i.total_cents for i in self.items)
@dataclass(frozen=True)
class Receipt:
method: str
amount_cents: int
reference: str
# ---------- pricing strategies ----------
class PricingStrategy(Protocol):
def price_cents(self, cart: Cart) -> int: ...
class RegularPricing:
def price_cents(self, cart: Cart) -> int:
return cart.subtotal_cents
class PercentOffPricing:
def __init__(self, percent: int) -> None:
if not 0 <= percent <= 100:
raise ValueError("percent out of range")
self._percent = percent
def price_cents(self, cart: Cart) -> int:
sub = cart.subtotal_cents
return sub - sub * self._percent // 100
class TieredPricing:
"""5% off from 100.00, 10% off from 500.00."""
def price_cents(self, cart: Cart) -> int:
sub = cart.subtotal_cents
percent = 10 if sub >= 50_000 else 5 if sub >= 10_000 else 0
return sub - sub * percent // 100
# ---------- payment strategies ----------
class PaymentStrategy(Protocol):
def pay(self, amount_cents: int) -> Receipt: ...
class CardPayment:
def __init__(self, card_number: str) -> None:
if not re.fullmatch(r"\d{16}", card_number):
raise ValueError("bad card")
self._card = card_number
def pay(self, amount_cents: int) -> Receipt:
return Receipt("card", amount_cents, f"card-{self._card[-4:]}")
class UpiPayment:
def __init__(self, vpa: str) -> None:
if not re.fullmatch(r"[\w.]+@\w+", vpa):
raise ValueError("bad upi id")
self._vpa = vpa
def pay(self, amount_cents: int) -> Receipt:
return Receipt("upi", amount_cents, f"upi-{self._vpa}")
class WalletPayment:
def __init__(self, balance_cents: int) -> None:
self.balance_cents = balance_cents
def pay(self, amount_cents: int) -> Receipt:
if amount_cents > self.balance_cents:
raise RuntimeError("insufficient balance")
self.balance_cents -= amount_cents
return Receipt("wallet", amount_cents, f"wallet-left-{self.balance_cents}")
# ---------- context ----------
class Checkout:
def __init__(self, pricing: PricingStrategy) -> None:
self._pricing = pricing
def quote(self, cart: Cart) -> int:
return self._pricing.price_cents(cart)
def complete(self, cart: Cart, payment: PaymentStrategy) -> Receipt:
if not cart.items:
raise ValueError("empty cart")
return payment.pay(self._pricing.price_cents(cart))
# ---------- client ----------
PRICING_BY_PLAN: dict[str, PricingStrategy] = {
"regular": RegularPricing(),
"member": PercentOffPricing(10),
"seasonal": TieredPricing(),
}
def pricing_for(plan: str) -> PricingStrategy:
try:
return PRICING_BY_PLAN[plan]
except KeyError:
raise ValueError(f"unknown plan {plan}") from None
if __name__ == "__main__":
cart = Cart((LineItem("tee", 3_000, 2), LineItem("cap", 5_000, 1)))
assert Checkout(pricing_for("regular")).quote(cart) == 11_000
assert Checkout(pricing_for("member")).quote(cart) == 9_900
assert Checkout(pricing_for("seasonal")).quote(cart) == 10_450
member = Checkout(pricing_for("member"))
assert member.complete(cart, UpiPayment("asha@okbank")).reference == "upi-asha@okbank"
assert member.complete(cart, CardPayment("4111111111111111")).reference == "card-1111"
wallet = WalletPayment(10_000)
member.complete(cart, wallet)
assert wallet.balance_cents == 100
try:
member.complete(cart, wallet)
raise AssertionError("second wallet payment should fail")
except RuntimeError:
pass
try:
pricing_for("memeber")
raise AssertionError("typo should be rejected")
except ValueError:
pass
print("strategy demo ok")
function assert(cond: boolean, msg = "assertion failed"): asserts cond {
if (!cond) throw new Error(msg);
}
interface LineItem { readonly sku: string; readonly unitCents: number; readonly qty: number }
interface Cart { readonly items: readonly LineItem[] }
interface Receipt { readonly method: string; readonly amountCents: number; readonly reference: string }
const subtotalCents = (cart: Cart): number =>
cart.items.reduce((sum, i) => sum + i.unitCents * i.qty, 0);
// ---------- pricing strategies ----------
interface PricingStrategy {
priceCents(cart: Cart): number;
}
class RegularPricing implements PricingStrategy {
priceCents(cart: Cart): number { return subtotalCents(cart); }
}
class PercentOffPricing implements PricingStrategy {
constructor(private readonly percent: number) {
if (percent < 0 || percent > 100) throw new RangeError("percent out of range");
}
priceCents(cart: Cart): number {
const sub = subtotalCents(cart);
return sub - Math.floor((sub * this.percent) / 100);
}
}
class TieredPricing implements PricingStrategy {
// 5% off from 100.00, 10% off from 500.00
priceCents(cart: Cart): number {
const sub = subtotalCents(cart);
const percent = sub >= 50_000 ? 10 : sub >= 10_000 ? 5 : 0;
return sub - Math.floor((sub * percent) / 100);
}
}
// ---------- payment strategies ----------
interface PaymentStrategy {
pay(amountCents: number): Receipt;
}
class CardPayment implements PaymentStrategy {
constructor(private readonly cardNumber: string) {
if (!/^\d{16}$/.test(cardNumber)) throw new Error("bad card");
}
pay(amountCents: number): Receipt {
return { method: "card", amountCents, reference: `card-${this.cardNumber.slice(-4)}` };
}
}
class UpiPayment implements PaymentStrategy {
constructor(private readonly vpa: string) {
if (!/^[\w.]+@\w+$/.test(vpa)) throw new Error("bad upi id");
}
pay(amountCents: number): Receipt {
return { method: "upi", amountCents, reference: `upi-${this.vpa}` };
}
}
class WalletPayment implements PaymentStrategy {
constructor(private balance: number) {}
get balanceCents(): number { return this.balance; }
pay(amountCents: number): Receipt {
if (amountCents > this.balance) throw new Error("insufficient balance");
this.balance -= amountCents;
return { method: "wallet", amountCents, reference: `wallet-left-${this.balance}` };
}
}
// ---------- context ----------
class Checkout {
constructor(private readonly pricing: PricingStrategy) {}
quote(cart: Cart): number { return this.pricing.priceCents(cart); }
complete(cart: Cart, payment: PaymentStrategy): Receipt {
if (cart.items.length === 0) throw new Error("empty cart");
return payment.pay(this.pricing.priceCents(cart));
}
}
// ---------- client ----------
const pricingByPlan = {
regular: new RegularPricing(),
member: new PercentOffPricing(10),
seasonal: new TieredPricing(),
} satisfies Record<string, PricingStrategy>;
type Plan = keyof typeof pricingByPlan; // "regular" | "member" | "seasonal"
// ---------- demo ----------
const cart: Cart = { items: [{ sku: "tee", unitCents: 3_000, qty: 2 }, { sku: "cap", unitCents: 5_000, qty: 1 }] };
const quote = (plan: Plan) => new Checkout(pricingByPlan[plan]).quote(cart);
assert(quote("regular") === 11_000);
assert(quote("member") === 9_900);
assert(quote("seasonal") === 10_450);
const member = new Checkout(pricingByPlan.member);
assert(member.complete(cart, new UpiPayment("asha@okbank")).reference === "upi-asha@okbank");
assert(member.complete(cart, new CardPayment("4111111111111111")).reference === "card-1111");
const wallet = new WalletPayment(10_000);
member.complete(cart, wallet);
assert(wallet.balanceCents === 100);
let failed = false;
try { member.complete(cart, wallet); } catch { failed = true; }
assert(failed, "second wallet payment should fail");
// quote("memeber") is a compile error: the plan names are a union type.
console.log("strategy demo ok");
A few details are worth pointing out because interviewers probe them:
- Strategies own their own data.
CardPaymenttakes the card number in its constructor;UpiPaymenttakes the UPI address. Thepay(amountCents)signature stays the same for every method, and the junk-drawer parameter list from the "before" code is gone. If you notice yourself adding a parameter to the strategy interface that only one implementation uses, that data belongs in that implementation's constructor instead. - Stateless strategies can be shared.
RegularPricingandTieredPricinghave no fields, andPercentOffPricinghas only an immutable one, so the catalog creates each once and hands the same instance to every checkout.WalletPaymentholds a balance, so each shopper needs their own. Know which kind each of your strategies is, because sharing a stateful strategy across threads is a classic bug. - Validation happens at construction. A
CardPaymentwith a nine-digit number can't exist. The context never has to ask "is this payment method valid?", because an invalid one couldn't have been handed to it. - The selection lives in one place.
PricingCatalog,PRICING_BY_PLANandpricingByPlanare the only code that knows concrete pricing classes exist. In TypeScript thesatisfiespluskeyof typeoftrick even turns the misspelt"memeber"from the "before" code into a compile error.
Pricing strategies in depth
Pricing is the canonical strategy example because real pricing rules multiply fast. A few situations come up again and again.
Composing strategies
Once you have pricing strategies, someone will ask: "what if a member shops during the seasonal sale?" There are three common answers, and each is just another strategy built from the others:
- Best of. Compute every eligible price and give the shopper the lowest. This is a strategy that holds a list of strategies.
- Stacking. Apply one discount, then another on the reduced amount. This is closer to a Decorator or a pipeline: each step transforms the previous total.
- Priority. Use the first strategy that applies. That's a small Chain of Responsibility.
The context doesn't change for any of these: Checkout still calls priceCents(cart) once, and the composition hides inside a strategy that delegates to others.
Who chooses the strategy?
There are four common places the decision can live, from most static to most dynamic:
| Chosen by | Example | Typical mechanism |
|---|---|---|
| Configuration at startup | "This storefront uses tiered pricing" | Dependency injection wires one implementation |
| A property of the request's subject | "Gold members get 10% off" | A lookup map from plan to strategy, as above |
| The user at runtime | "Pay with UPI" | The UI passes the chosen strategy as a parameter |
| The data itself | "Carts over 500.00 get the bulk rule" | A selector function or a "best of" strategy |
The choice should happen once, at a boundary. One switch or map lookup that picks the strategy is fine; the smell is the same switch repeated in several places.
Payment strategies in depth
Payment looks like the same pattern, but a real payment flow is usually a short protocol rather than one call: authorise, then capture or void, sometimes with a redirect to a bank page in between. Two consequences follow.
The strategy interface grows past one method. A production PaymentStrategy might have authorize, capture and refund. That is still a strategy (a family of interchangeable implementations of one capability), but it can no longer be replaced by a single function, and the interface needs more careful design. Resist adding methods that only one provider supports. "Save card for later" belongs on a separate interface that CardPayment also implements, which is the interface segregation principle at work.
Say this in the interview
"Pricing and payment vary independently, so I'll make them two strategy interfaces rather than one. Pricing is chosen per storefront and injected into the checkout; payment is chosen by the shopper per order, so it's a parameter of complete."
Functions as strategies
In Java 8+, Python and TypeScript, a strategy with a single method is just a function with a name. Writing a class for it is often ceremony. PricingStrategy in the Java sample is annotated @FunctionalInterface, so any lambda with the right shape is a pricing strategy:
import java.util.*;
record Cart(long subtotalCents, int units) {}
@FunctionalInterface
interface PricingStrategy {
long priceCents(Cart cart);
static PricingStrategy percentOff(int percent) {
return cart -> cart.subtotalCents() - cart.subtotalCents() * percent / 100;
}
// a strategy built from other strategies: the shopper gets the lowest price
static PricingStrategy bestOf(PricingStrategy... options) {
List<PricingStrategy> all = List.of(options);
return cart -> all.stream().mapToLong(s -> s.priceCents(cart)).min().orElseThrow();
}
}
class Demo {
public static void main(String[] args) {
PricingStrategy regular = Cart::subtotalCents; // method reference
PricingStrategy member = PricingStrategy.percentOff(10);
PricingStrategy bulk = cart -> cart.units() >= 10 // inline lambda
? cart.subtotalCents() - cart.subtotalCents() * 15 / 100
: cart.subtotalCents();
PricingStrategy best = PricingStrategy.bestOf(regular, member, bulk);
Cart small = new Cart(10_000, 2);
Cart big = new Cart(10_000, 12);
assert best.priceCents(small) == 9_000; // member wins
assert best.priceCents(big) == 8_500; // bulk wins
// The JDK is full of these: Comparator is a strategy for ordering.
List<String> skus = new ArrayList<>(List.of("cap", "tee", "belt"));
skus.sort(Comparator.comparing(String::length).thenComparing(Comparator.reverseOrder()));
assert skus.equals(List.of("tee", "cap", "belt"));
System.out.println("function strategies ok");
}
}
from collections.abc import Callable
from dataclasses import dataclass
from functools import partial
@dataclass(frozen=True)
class Cart:
subtotal_cents: int
units: int
Pricing = Callable[[Cart], int]
def regular(cart: Cart) -> int:
return cart.subtotal_cents
def percent_off(percent: int, cart: Cart) -> int:
return cart.subtotal_cents - cart.subtotal_cents * percent // 100
def bulk(cart: Cart) -> int:
return percent_off(15, cart) if cart.units >= 10 else cart.subtotal_cents
def best_of(*options: Pricing) -> Pricing:
return lambda cart: min(option(cart) for option in options)
member: Pricing = partial(percent_off, 10) # parameterised strategy
best = best_of(regular, member, bulk)
assert best(Cart(10_000, 2)) == 9_000
assert best(Cart(10_000, 12)) == 8_500
# The standard library takes strategies everywhere: key= is one.
skus = ["cap", "tee", "belt"]
assert sorted(skus, key=lambda s: (len(s), [-ord(c) for c in s])) == ["tee", "cap", "belt"]
print("function strategies ok")
function assert(cond: boolean, msg = "assertion failed"): asserts cond {
if (!cond) throw new Error(msg);
}
interface Cart { readonly subtotalCents: number; readonly units: number }
type Pricing = (cart: Cart) => number;
const regular: Pricing = (cart) => cart.subtotalCents;
const percentOff = (percent: number): Pricing => (cart) =>
cart.subtotalCents - Math.floor((cart.subtotalCents * percent) / 100);
const bulk: Pricing = (cart) => (cart.units >= 10 ? percentOff(15)(cart) : cart.subtotalCents);
const bestOf = (...options: Pricing[]): Pricing => (cart) =>
Math.min(...options.map((option) => option(cart)));
const best = bestOf(regular, percentOff(10), bulk);
assert(best({ subtotalCents: 10_000, units: 2 }) === 9_000);
assert(best({ subtotalCents: 10_000, units: 12 }) === 8_500);
// Array.prototype.sort takes a comparison strategy.
const skus = ["cap", "tee", "belt"].sort((a, b) => a.length - b.length || b.localeCompare(a));
assert(skus.join(",") === "tee,cap,belt");
console.log("function strategies ok");
Partial application (partial(percent_off, 10)) and closures (percentOff(10)) do the job a constructor did in the class version: they bake configuration into the strategy. bestOf shows that composing strategies is just higher-order functions.
When to keep the class
Functions are the better default for one-method strategies with little or no configuration. Reach for a class (or a record) when:
- The strategy has several operations that must stay consistent, like
authorize,captureandrefund. A bundle of three loose functions can be mixed up; a class can't. - It needs a name or identity at runtime. Logging "priced with TieredPricing v2", showing the method in an admin UI, serialising the choice to a database or comparing two strategies for equality are all awkward with anonymous lambdas.
- It has meaningful state or dependencies. A wallet with a balance, or a loyalty rule that needs a repository, reads more clearly as an object with a constructor.
- It needs validation at creation. A constructor that rejects
percent = 140is a clear, testable home for that rule.
In an interview, it's worth saying both out loud: "I'll define a PricingStrategy interface. In Java it's a functional interface, so simple rules can be lambdas, and the ones that need configuration or a name are classes."
Testing benefit
Each concrete strategy can be tested alone with only the inputs it needs, and the context can be tested with a trivial strategy such as cart -> 1234 plus a fake payment that records the amount it was asked to charge. Three pricing rules and three payment methods then need roughly 3 + 3 tests plus a few for the workflow, not 3 × 3. A strategy interface is a test seam, the idea covered in common LLD mistakes.
Real-world uses
java.util.Comparator.List.sort,Collections.sort,TreeMapandPriorityQueueall take a comparator that decides ordering. The sorting algorithm is the context; the comparison is the strategy.Comparator.comparing(...).thenComparing(...)is strategy composition built into the JDK.ThreadPoolExecutor'sRejectedExecutionHandler. When the queue is full, the executor delegates to a pluggable policy. The JDK shipsAbortPolicy(the default, which throws),CallerRunsPolicy,DiscardPolicyandDiscardOldestPolicy.- AWT and Swing
LayoutManager. AContainerdelegates the positioning of its children to whichever layout manager it holds (FlowLayout,BorderLayout,GridLayout), andsetLayoutswaps it at runtime. - Python's
key=andsorted.sorted,min,maxandlist.sortaccept a key function, which is a function-as-strategy for "what to compare by".json.dumps(default=...)takes a strategy for serialising objects it doesn't know. - JavaScript's
Array.prototype.sort(compareFn), the same idea asComparator. - Passport.js. The Node authentication library calls its pluggable login mechanisms "strategies" (
passport-local,passport-jwt, OAuth providers), registered withpassport.use(...)and selected by name per route. - LLD case studies. The parking lot uses strategies for fee calculation and spot allocation, and the elevator system for scheduling which car answers a call.
When NOT to use it
Strategy has real costs: more types, an indirection to follow when reading the code, and a selection mechanism that has to live somewhere. Skip it when:
- There are two branches and no sign of a third.
if (express) fee = 500 else fee = 0doesn't need an interface. Add the pattern when the third variant arrives or the interviewer tells you it's coming. Adding it speculatively is the over-patterning mistake. - The variants differ only by data, not by algorithm. If "member", "staff" and "student" are all "take N percent off" with different N, that's one class with a field, or an enum with a percentage, not three strategies.
- The algorithm needs the context's internals. If every strategy reaches back into the context for five fields, the "separate algorithm" is really part of the context. Pulling it out just spreads one concept across two places. That's feature envy, not decoupling.
- The behaviour depends on the object's own lifecycle. If which algorithm runs is decided by what state the object is in, and the algorithm itself moves the object to a new state, you want State, not Strategy.
- The client has to understand every strategy to choose one. If picking the right variant requires deep knowledge of how each one works, the abstraction isn't hiding much. Consider letting the strategies declare when they apply (
supports(cart)) and selecting automatically.
Related patterns
| Pattern | How it relates | The difference |
|---|---|---|
| State | Identical class diagram: a context holding a swappable object behind an interface. | In State, the state objects trigger transitions and the context's behaviour changes as it moves through a lifecycle. In Strategy, the client picks the algorithm, and the strategy doesn't swap itself out. |
| Template Method | Both vary part of an algorithm. | Template Method fixes the skeleton in a base class and varies steps through inheritance at compile time. Strategy swaps the whole algorithm through composition, at runtime. |
| Command | Both wrap behaviour in an object. | A command is a request (what to do, with its arguments, often undoable and queueable). A strategy is how to do one step of a job the context already knows it must do. |
| Decorator | Both use composition to change behaviour. | A decorator wraps an object and keeps its interface, adding behaviour around it (like stacking discounts). A strategy replaces the algorithm inside the context. Decorator changes the "skin"; Strategy changes the "guts". |
| Specification | Specifications are often used to select a strategy. | A specification answers "does this apply?"; a strategy answers "how do we compute it?". Pricing engines frequently pair them: rule = specification + strategy. |
| Factory Method / dependency injection | Usually how the client creates and supplies the strategy. | They solve who constructs the strategy, not what it does. |
The smell that suggests it
You probably want Strategy when you see:
- A conditional on a "type", "mode" or "kind" value that picks an algorithm, especially if it keeps growing:
if (plan == "member") ... else if (plan == "seasonal") .... - The same conditional in more than one method, such as one
switchonpaymentMethodinvalidate, another inpayand a third inrefund. Each new method means three edits. - Parameters that are only used by one branch, like
cardNumberandupiIdside by side in one signature. - Boolean flags that change how a computation runs:
calculate(cart, isMember, isSale, isFirstOrder). Each flag doubles the paths. - Tests that need combinations of unrelated setups to cover one rule.
The refactoring is mechanical: extract each branch into a class (or function) implementing a common interface, pass the chosen one into the context, and move the decision to the client. Martin Fowler's catalogue calls this "Replace Conditional with Polymorphism".
Interview questions
- "What's the difference between Strategy and State? The diagrams look the same." The structure is identical; the intent and the control flow differ. With Strategy, the client chooses the algorithm and the strategy never changes itself. A sorted list doesn't care which comparator it's given. With State, the object moves through a lifecycle, and the state objects decide the next state: a vending machine in
HasMoneybecomesDispensing. If the variant is chosen from outside and stays put, it's Strategy. If it changes as a result of operations, it's State. - "Why not just use a switch statement?" A single
switchthat picks an algorithm in one place is fine, and a strategy factory often contains exactly that. The problem is aswitchrepeated across methods, or one that keeps growing in a class that also does other things. Strategy lets you add a variant by adding code, not by editing tested code, and lets you test each variant alone. - "Should the strategy be a constructor argument or a method parameter?" It depends on its lifetime. If it's chosen once per configured object (a storefront's pricing), inject it in the constructor. If it's chosen per call (the payment method for this order), pass it as a parameter. A setter that swaps it later is a third option, but it makes the object's behaviour time-dependent and raises thread-safety questions.
- "Your strategies need different data. How do you keep a single interface?" Put the data that every strategy needs in the method signature, and give each strategy the extra data it alone needs through its constructor.
CardPayment(cardNumber)andUpiPayment(vpa)both implementpay(amount). - "When would you use a lambda instead of a strategy class?" For one-method strategies with little configuration, like comparators, key extractors or simple pricing rules. Use a class when the strategy has several related methods, needs a name for logs or persistence, holds state or dependencies, or validates its configuration.
- "How would you support a member shopping during a sale?" Without touching the context, by adding a composite strategy: "best of" (lowest price wins), "stacked" (apply in sequence, closer to a decorator chain) or "first applicable" (a chain). Clarify the business rule first, because which one is correct is a product decision.
- "Are strategies thread-safe?" Stateless or immutable strategies are, and can be shared as singletons across all requests. Stateful ones, like a wallet with a balance or a rate limiter with counters, either need one instance per user or proper synchronisation. Say which kind each of yours is.
- "How does Strategy relate to the open-closed principle?" It's one of the most direct ways to achieve it. The context is closed for modification (it only knows the interface) and the system is open for extension (new strategies are new classes). The one place that still changes is the client's selection code, which is why you keep it small and in one place.
Further reading
- Behavioral patterns overview: the grouped page this one expands
- Open-closed principle: the principle Strategy most directly serves
- State and Template Method: the two patterns most often confused with it
- Pattern selection guide: Strategy vs State, Command vs Strategy and Template Method vs Strategy side by side
- Parking lot case study: fee and allocation strategies in a full design