Strategy puts each version of an algorithm (each way to pay, sort, compress or price something) in its own class behind one shared interface. The object that needs the algorithm holds one of those classes in a field and calls it through the interface, without asking which version it has. You can then add a version, or swap one at runtime, without editing that object. It is the pattern behind every sort that accepts a comparator, and the standard cure for an if/else chain that grows with every new requirement.
Think of it like
Lenses on a camera
A camera body has one standard lens mount. A wide-angle, a portrait or a zoom lens all click into that mount, and the shutter button works the same with every one of them. When a new lens comes out you buy the lens, not a new camera. The body is the context, the mount is the strategy interface, each lens is a concrete strategy, and you, choosing the lens for the shot, are the client.
The problem
An online store's checkout started with card payments. Then the business added UPI. The quickest change is a type parameter and an if/else inside Checkout, with one private method per payment method. This is exactly the Before version in the visualizer above.
class Checkout {
constructor(
private cardNo: string,
private upiId: string,
) {}
checkout(type: string, amount: number): string {
if (type === "card") {
return this.payByCard(amount);
} else if (type === "upi") {
return this.payByUpi(amount);
}
throw new Error(`Unknown type: ${type}`);
}
private payByCard(amount: number): string {
return `₹${amount} via card ${this.cardNo.slice(-4)}`;
}
private payByUpi(amount: number): string {
return `₹${amount} via UPI ${this.upiId}`;
}
}
const cart = new Checkout("42424242", "asha@ok");
cart.checkout("card", 499); // "₹499 via card 4242"
cart.checkout("upi", 250); // "₹250 via UPI asha@ok"With two payment methods this is short and readable. The trouble starts when the third one arrives, and the fourth, and when other features need the same branching:
- Every new method edits
Checkout. PayPal needs a new field, a new constructor parameter, a new branch and a new private method, all inside the class that every payment goes through. The class is never closed for modification, which is what the open/closed principle in SOLID Principles asks for. - One class, many reasons to change. A card-network rule, a UPI API update and a checkout flow change all land in the same file.
- Coarse tests. To test UPI you build a whole
Checkout, card number included. Each edit to the shared if/else means re-testing every branch. - Merge conflicts. Two teams adding a wallet and a pay-later option in the same sprint both edit the same method.
- The switch spreads. Refunds, fees and receipt text soon need their own
if (type === ...)chain, so each new method has to be added in several places, and missing one is a bug.
The pattern
Intent: define a family of algorithms, put each one in its own class, and make them interchangeable behind one interface, so the algorithm can change independently of the code that uses it.
- Context (
Checkout) - The object that needs the work done. It holds a reference to a strategy, typed as the interface, and forwards the work to it:
checkout(amount)callsthis.strategy.pay(amount). It never names a concrete strategy. - Strategy (
PaymentStrategy) - The interface every variant implements. Here it has one method,
pay(amount). It defines what the context may rely on, and nothing more. - Concrete strategy (
CardPayment,UpiPayment) - One class per algorithm. Each keeps the data only it needs (
cardNo,upiId) and implementspayits own way. - Client
- The code that chooses a strategy, creates it and hands it to the context, through the constructor or a setter like
setStrategy(s). The choice lives here, not in the context.
The context depends only on the interface (an association from Checkout to PaymentStrategy), and each concrete strategy implements that interface. Data reaches a strategy in two ways: per-call data as arguments (amount), and data that belongs to one variant through that strategy's constructor (cardNo). Because Checkout no longer knows any payment method, adding one cannot break it.
What the visualizer shows
Press Play in the visualizer at the top of the page, or step through it with the arrow buttons. It really runs the classes in the code panel and draws what happened. The line that is running is highlighted in the code, and the caption under the stage explains each step.
- Class diagram: the classes and methods the current step uses light up. Amber is the code running now, sky blue the caller waiting for an answer, green something just created or returned, and violet the interface that declares the method being called. When
cartcallspay, watchPaymentStrategylight up in violet whileCardPayment(and laterUpiPayment) runs. - Objects at runtime: the live objects, such as
cart : Checkoutwith its fieldstrategy = card, and an arrow from that field to the object it points to. The message in flight travels between the boxes with its arguments or return value. When the client swaps the strategy, the field turns intostrategy = upiand the arrow moves. - Sequence of calls: one lifeline per object and one row per message, growing step by step. The client sends
checkout(...)twice, and the matchingpay(...)goes tocardthe first time and toupithe second.
The Before / With Strategy toggle switches between the if/else version (one Checkout class that calls its own payByCard and payByUpi) and the pattern. Add PayPal applies the change request to whichever version is shown: changed classes get a badge in the class diagram (new class or edited +6 −1), and the Change request panel beside the code counts what each version had to change. On a phone the three views sit behind a Classes / Objects / Sequence switch.
Walkthrough
- 1
Create a strategy
With With Strategy selected, the client first runs
new CardPayment("42424242"). The objectcardappears, holdingcardNo, the one piece of data only card payments need. - 2
Create the context with it
new Checkout(card)createscartwithstrategy = card. From now oncartknows only that it holds somePaymentStrategy. - 3
Call the context
The client calls
cart.checkout(499). The client does not pass a payment type, because the choice was already made when the strategy was plugged in. - 4
Delegate through the interface
cartcallspay(499)on the object in itsstrategyfield.payis declared byPaymentStrategy; the object is aCardPayment, soCardPayment.payruns. No branch was evaluated to get here. - 5
Return the result
"₹499 via card 4242"travels back fromcardtocartand then to the client. - 6
Swap the strategy at runtime
The shopper switches to UPI. The client creates
upiand callscart.setStrategy(upi), socart.strategynow points toupiinstead ofcard.Checkout's code did not change. - 7
Same call, different behavior
cart.checkout(250)runs exactly the same line,this.strategy.pay(amount), but this timeUpiPayment.payanswers:"₹250 via UPI asha@ok". - 8
Add PayPal (change request)
With Add PayPal applied, the run continues: the client creates
paypal, plugs it in withsetStrategy(paypal), andcart.checkout(120)returns"₹120 via PayPal asha@x.in". The only new code is thePayPalPaymentclass and three client lines.
Before and after
Without the pattern
- One
Checkoutclass holds every method's data and logic - The method is chosen by an if/else on a
typestring, on every call - Adding PayPal edits
Checkout: field, constructor, branch and method - Each payment method is tested through the whole class
- Fewer classes; easy to read while there are two branches
With Strategy
- Each payment method is its own small class behind
PaymentStrategy Checkoutdelegates with one line and never branches- Adding PayPal adds one class; existing classes stay untouched
- Each strategy is tested alone;
Checkoutis tested with a fake - The method can be swapped at runtime with
setStrategy
| Change request: add PayPal | Before | With Strategy |
|---|---|---|
| Existing classes edited | 1 (Checkout) | 0 |
| New classes | 0 | 1 (PayPalPayment) |
| Lines changed in existing classes | 7 (+6 −1) | 0 |
The seven lines in the Before version are the constructor line that gains an email parameter (one line removed, one added), a two-line else if branch and a three-line payByPaypal method. With Strategy, the new PayPalPayment class is the only class that changes. In both versions the client gains lines too, because something has to say "use PayPal".
Variations
Strategies as plain functions
When the interface has a single method, a function type does the same job with less ceremony: type PaymentStrategy = (amount: number) => string. TypeScript and Python pass functions directly; Java uses a functional interface so callers can pass lambdas; C++ uses std::function or a template parameter. A one-off variant, such as paying with store credit, is then just a lambda with no class at all. The second implementation below shows this version in all four languages.
Choosing a strategy without another if/else
If the client picks the strategy with if (method === "card") ... else if ..., the old conditional is back, just in a different file. Use a lookup table (a map from a name to a factory) or a factory function, in one place at the edge of the system where the request is parsed. Adding PayPal is then one new class plus one new entry.
type Build = (c: Customer) => PaymentStrategy;
const PAYMENT_METHODS = new Map<string, Build>([
["card", (c) => new CardPayment(c.cardNo)],
["upi", (c) => new UpiPayment(c.upiId)],
["paypal", (c) => new PayPalPayment(c.email)],
]);
function strategyFor(method: string, c: Customer): PaymentStrategy {
const build = PAYMENT_METHODS.get(method);
if (!build) throw new Error(`Unsupported payment method: ${method}`);
return build(c);
}More variations
| Variation | Use it when | Example |
|---|---|---|
| Shared stateless strategy | The strategy has no fields, so one instance can serve every caller and thread | Java's String.CASE_INSENSITIVE_ORDER is a single shared Comparator |
| Default (null) strategy | The context should work before anyone configures it, without null checks | A NoDiscount strategy that returns the price unchanged; see Null Object |
| Chosen by configuration | The variant is a deployment decision | Compression algorithm or storage backend read from config at startup and wired in by a DI container (Dependency Injection) |
| Chosen per request | Each call may need a different variant | Payment method picked by the shopper; response encoding picked from the Accept-Encoding header |
| Compile-time strategy | The variant is fixed per use site and speed matters | C++ comparator and allocator template parameters such as std::map<K, V, Compare> |
In real code
| Where | Context | Strategy |
|---|---|---|
| Java collections | list.sort(...), Collections.sort, TreeMap | A Comparator, often built with Comparator.comparing(Person::getAge) |
| JavaScript arrays | Array.prototype.sort | The compareFn argument, e.g. (a, b) => a - b. Without it, elements are compared as strings, so [10, 9, 1].sort() gives [1, 10, 9] |
| Python | sorted(), list.sort(), min(), max() | The key= function, e.g. sorted(words, key=len) |
| C++ standard library | std::sort, std::set, std::map | A comparator such as std::greater<int>(), passed as an argument or a template parameter |
| Java thread pools | ThreadPoolExecutor | A RejectedExecutionHandler: AbortPolicy (the default), CallerRunsPolicy, DiscardPolicy or DiscardOldestPolicy |
| Spring | Any bean that depends on an interface | The implementation the container injects; @Autowired Map<String, PaymentStrategy> receives every implementation keyed by bean name, a ready-made registry |
| Node.js auth | Passport.js | Login methods are literally called strategies: passport.use(new LocalStrategy(...)) |
| NGINX | An upstream block | The load-balancing method: round robin by default, or least_conn, ip_hash, hash |
| Python retries | The tenacity library's @retry | Pluggable stop= and wait= policies, e.g. stop_after_attempt(3) and wait_exponential() |
The same shape appears in application code wherever one step has several interchangeable rules: payment gateways, shipping-cost and tax rules per country, pricing and discount rules, route planning (fastest, shortest, avoid tolls), cache eviction policies in Design an LRU Cache (Class Design), and retry and backoff policies in Retry with Backoff & Jitter.
When to use it, and when not to
Reach for Strategy when
- There are several interchangeable ways to do one task, and more are coming
- The choice is made at runtime: per user, per request, per tenant or by config
- The variants change for different reasons or are owned by different teams
- The same type-code conditional appears in more than one place
- You want to test each variant alone, or pass a fake in tests
Keep the if/else when
- There are two branches, they are stable, and they live in one place
- Each variant is a one-line expression (a function argument may be enough)
- The variants need very different inputs, so one interface would be forced
- The behavior depends on the object's own lifecycle (that is State)
- Nobody has asked for a third variant yet (YAGNI)
Strategy vs similar patterns
Several patterns put behavior behind an interface, so their class diagrams look alike. Ask two questions to tell them apart: what varies, and who decides which variant runs, and when.
| Pattern | What varies | Who chooses, and when | Built with |
|---|---|---|---|
| Strategy | One algorithm: how a task is done | The client (or config), from outside; can be swapped at runtime. Strategies do not know about each other | Composition: the context holds the interface |
| State | Behavior that depends on the object's current state | The state objects (or the context) switch to the next state as events happen; the client usually does not choose | Composition, and states know their successors |
| Template Method | Some steps of a fixed algorithm | Fixed when you pick a subclass; cannot change at runtime | Inheritance: a base class calls overridable steps |
| Command | Which request is executed | Whoever creates the command; the invoker just runs it, and may queue, log or undo it | An object that packages an action and its arguments |
| Bridge | Two dimensions at once (e.g. shapes and renderers) | Chosen when the object is built, usually for its lifetime | Composition between two class hierarchies |
| Decorator | Extra behavior added around an object | Whoever wraps it; wrappers stack | A wrapper with the same interface as the object it wraps |
Implementation
The visualizer's scenario as a complete program: a PaymentStrategy interface, card and UPI strategies, a Checkout context, and PayPal added as one new class. Amounts are whole rupees to keep the example short.
from abc import ABC, abstractmethod
class PaymentStrategy(ABC):
@abstractmethod
def pay(self, amount: int) -> str: ...
class CardPayment(PaymentStrategy):
def __init__(self, card_no: str) -> None:
self._card_no = card_no
def pay(self, amount: int) -> str:
return f"₹{amount} via card {self._card_no[-4:]}"
class UpiPayment(PaymentStrategy):
def __init__(self, upi_id: str) -> None:
self._upi_id = upi_id
def pay(self, amount: int) -> str:
return f"₹{amount} via UPI {self._upi_id}"
# The change request: one new class. Nothing else is edited.
class PayPalPayment(PaymentStrategy):
def __init__(self, email: str) -> None:
self._email = email
def pay(self, amount: int) -> str:
return f"₹{amount} via PayPal {self._email}"
class Checkout:
"""The context: holds a strategy and delegates to it."""
def __init__(self, strategy: PaymentStrategy) -> None:
self._strategy = strategy
def set_strategy(self, strategy: PaymentStrategy) -> None:
self._strategy = strategy
def checkout(self, amount: int) -> str:
return self._strategy.pay(amount)
if __name__ == "__main__":
cart = Checkout(CardPayment("42424242"))
print(cart.checkout(499)) # ₹499 via card 4242
cart.set_strategy(UpiPayment("asha@ok"))
print(cart.checkout(250)) # ₹250 via UPI asha@ok
cart.set_strategy(PayPalPayment("asha@x.in"))
print(cart.checkout(120)) # ₹120 via PayPal asha@x.inKey takeaways
- Strategy puts each variant of an algorithm in its own class behind one interface; the context holds that interface and delegates, so it never branches on a type code.
- Adding a variant means adding a class, not editing one. In the visualizer's "Add PayPal" request: 0 existing classes edited with Strategy, versus
Checkoutedited by 7 lines without it. - The client (or a registry, factory or config) chooses the strategy, once, at the edge. The context can switch it at runtime through a setter.
- When the interface has one method, a function is enough:
sort(compareFn),sorted(key=...)and Java lambdas are all Strategy. - Strategy and State share a class diagram; the difference is who switches the behavior and why. Template Method varies steps by inheritance instead.
- Two stable branches in one place do not need Strategy. Refactor when the third variant or the second copy of the switch appears.
Common pitfalls
- Moving the if/else instead of removing it: if
Checkoutstill doesif (type === "card") this.strategy = new CardPayment(...), nothing improved. Choose the strategy outside the context, through a map or a factory. - A bloated strategy interface: parameters that only one strategy uses, or methods that some strategies implement by throwing. Pass variant-specific data through the strategy's constructor and keep the interface to what every variant needs.
- Sharing a strategy that holds per-user or per-request state (like a card number) between users or threads. Only stateless strategies are safe to share as a single instance.
- Leaking the concrete type: a context that checks
instanceof CardPaymentor casts its strategy has rebuilt the conditional the pattern was meant to remove.
Interview tips
- In LLD rounds (parking-lot fees, elevator scheduling, pricing, notifications) name the axis of variation out loud, define the strategy interface first, implement one or two concrete strategies, then show how a new one plugs in without edits.
- Expect "how is this different from State or Template Method?". Answer with who chooses (client vs the states themselves vs a subclass) and when (runtime vs compile time).
- Say how strategies get selected (a map, a factory or DI) so the interviewer sees the if/else does not simply move, and mention the lambda form for single-method strategies.
Real-world applications
- Sorting and ordering with pluggable comparators: Java
Comparator, JavaScriptcompareFn, Pythonkey=, C++ comparator objects. - Payment gateways, shipping-cost, tax and discount rules that differ by region, customer or campaign.
- Load-balancing algorithms (round robin, least connections, IP hash) and rate-limiting algorithms.
- Retry and backoff policies, and the rejection policy of a thread pool.
- Cache eviction policies (LRU, LFU, FIFO) and compression or serialization formats chosen per request.
- Authentication methods in Passport.js, which calls each one a strategy.
Test yourself
In the checkout example with Strategy, which participant decides that UPI is used for the second payment?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.