These are the notes for Low-Level Design (LLD) episode 34, the first behavioural pattern. Behavioural patterns are about how objects share work and talk to each other (the other two families were creational, about making objects, and structural, about putting objects together). Strategy is the one you will use most: it replaces a growing if-else chain of algorithms with small, swappable objects. We start with three ways to reach a railway station, watch Asha's food-app checkout crash when a new way to pay is added, and invent the pattern as the fix. Then we write strategies as lambdas, see that Java's own Comparator is a strategy, pick strategies from a Map, and meet one compile error you will see in real projects. Every program was actually run with javac Main.java && java -cp . Main (Java 21). Outputs are real.
1. The real-life idea: same trip, different ways
| Going to the station | In code |
|---|---|
| You, at the door: the goal (reach the station) never changes | The context: the object that needs a job done but doesn't care how |
| "A way to get there": any way that reaches the station | The strategy interface: one method every way must have |
| Auto, metro, walking: each works differently | Concrete strategies: one class per algorithm |
| It's raining, so you take the auto: decided at the last minute | Swapping at runtime: changing the strategy while the program runs |
An algorithm is a step-by-step way to do a job (adding a 2% fee and charging a card is an algorithm). A strategy is one algorithm wrapped in its own object. Runtime means while the program is running, as opposed to compile time, when you write and compile it.
2. The problem: an if-else checkout
Asha's food delivery app has a Checkout whose pay method knows every way to pay: UPI pays the amount, a card adds a 2% fee, cash on delivery (COD) adds 20 rupees. Then the app team ships "pay by wallet" before anyone has edited Checkout:
class Checkout { // knows EVERY way to pay
int pay(String method, int amount) {
if (method.equals("upi")) {
System.out.println("UPI: paid " + amount + " from your bank");
return amount;
} else if (method.equals("card")) {
int fee = amount * 2 / 100; // card fee: 2%
System.out.println("Card: paid " + (amount + fee) + " (fee " + fee + ")");
return amount + fee;
} else if (method.equals("cod")) {
System.out.println("Cash on delivery: pay " + (amount + 20) + " at the door");
return amount + 20;
} else {
throw new IllegalArgumentException("Unknown payment method: " + method);
}
}
}
public class Main {
public static void main(String[] args) {
Checkout checkout = new Checkout();
checkout.pay("upi", 450);
checkout.pay("card", 450);
checkout.pay("cod", 450);
checkout.pay("wallet", 450); // the new feature from the app team
}
}
UPI: paid 450 from your bank
Card: paid 459 (fee 9)
Cash on delivery: pay 470 at the door
Exception in thread "main" java.lang.IllegalArgumentException: Unknown payment method: wallet
at Checkout.pay(Main.java:14)
at Main.main(Main.java:24)
IllegalArgumentException is the standard exception for "this argument is not allowed"; here it is thrown by the else branch because nobody added a wallet branch.
Why it failed
Checkoutknows every payment algorithm. Each new way to pay means opening the same method, editing it and re-testing all the old ways. With twenty ways to pay you get one giant method that every team edits (and breaks).- It breaks the Open-Closed Principle (episode 13): code should be open for extension (you can add behaviour) but closed for modification (you don't edit working code to do it).
- Separate what changes (how we pay) from what stays the same (checkout needs someone to "pay this amount"). Put each way to pay in its own class and plug in the one you need.
3. The fix: one class per algorithm
interface PaymentStrategy { int pay(int amount); } // the strategy interface
class UpiPayment implements PaymentStrategy { // concrete strategies
public int pay(int a) { System.out.println("UPI: paid " + a + " from your bank"); return a; }
}
class CardPayment implements PaymentStrategy {
public int pay(int a) {
int fee = a * 2 / 100;
System.out.println("Card: paid " + (a + fee) + " (fee " + fee + ")"); return a + fee;
}
}
class WalletPayment implements PaymentStrategy { // NEW: Checkout is not touched
public int pay(int a) { System.out.println("Wallet: paid " + a + ", 5 cashback"); return a - 5; }
}
class Checkout { // the context
private PaymentStrategy strategy;
Checkout(PaymentStrategy s) { strategy = s; }
void setStrategy(PaymentStrategy s) { strategy = s; }
int checkout(int amount) { return strategy.pay(amount); }
}
public class Main {
public static void main(String[] args) {
Checkout c = new Checkout(new UpiPayment());
c.checkout(450);
c.setStrategy(new CardPayment()); c.checkout(450); // swap at runtime
c.setStrategy(new WalletPayment());
System.out.println("charged: " + c.checkout(450));
}
}
UPI: paid 450 from your bank
Card: paid 459 (fee 9)
Wallet: paid 450, 5 cashback
charged: 445
PaymentStrategyis the strategy interface: one method,pay.UpiPayment,CardPayment,WalletPaymentare concrete strategies.Checkoutis the context: it holds aPaymentStrategyfield (through the interface, never a concrete class) and simply callsstrategy.pay(amount).setStrategyswaps the algorithm at runtime, on the same object.- Adding
WalletPaymentmeant writing one new class;Checkoutwas not touched. That's the Open-Closed Principle in action.
4. It has a name: the Strategy pattern
+---------------------------+ +-------------------------+
| Checkout «context» |<>------>| «interface» |
| - strategy | has one| PaymentStrategy |
| + setStrategy(s) | | + pay(amount): int |
| + checkout(amount) | +-------------------------+
+---------------------------+ ^ ^ ^
: : : (implements)
UpiPayment CardPayment WalletPayment
The classic intent (SourceMaking): "Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it." Encapsulate means wrap up and hide inside; interchangeable means any one can replace another.
| Role | In our example | Job |
|---|---|---|
| Context | Checkout |
Holds a strategy, delegates the work to it |
| Strategy | PaymentStrategy |
The common interface |
| Concrete strategy | UpiPayment, CardPayment, WalletPayment |
One algorithm each |
| Client | Main |
Chooses which strategy to give the context |
What Strategy bought us
| Before (if-else) | After (Strategy) |
|---|---|
A new way to pay = edit Checkout |
A new way to pay = add a class; Checkout stays closed for modification |
| Test the whole checkout for every change | Test each algorithm alone: new CardPayment().pay(450) must return 459 |
| The algorithm is fixed when you write the code | Swap at runtime: the user picks, or a sale switches the discount at midnight |
| Every team edits one method | Each team edits its own file |
Tip: keep strategies stateless. Stateless means the object has no fields that change. Then one UpiPayment object can be shared safely by every checkout in the app (even across threads).
5. Strategies as lambdas, and Comparator
A functional interface is an interface with exactly one abstract method (episode 5). A lambda (bill -> bill * 90 / 100) is a short way to write that one method. So a one-method strategy can be a lambda instead of a whole class. @FunctionalInterface asks the compiler to check that the interface really has just one abstract method.
A Comparator is an object that decides which of two items comes first. List.sort takes one, so Comparator is Java's built-in sorting strategy: same list, same sort method, different order.
import java.util.*;
@FunctionalInterface
interface Discount { int apply(int bill); } // ONE abstract method
public class Main {
public static void main(String[] args) {
Discount none = bill -> bill;
Discount diwali = bill -> bill * 90 / 100; // 10% off
Discount flat50 = bill -> bill >= 300 ? bill - 50 : bill;
for (Discount d : List.of(none, diwali, flat50))
System.out.println("bill 450 -> " + d.apply(450));
record Restaurant(String name, double rating, int minutes) { }
List<Restaurant> list = new ArrayList<>(List.of(
new Restaurant("Chai Point", 4.1, 25), new Restaurant("Dosa Hut", 4.6, 40),
new Restaurant("Biryani Box", 4.3, 15)));
list.sort(Comparator.comparingInt(Restaurant::minutes)); // strategy 1
System.out.println("fastest: " + list.get(0).name());
list.sort(Comparator.comparingDouble(Restaurant::rating).reversed()); // 2
System.out.println("best: " + list.get(0).name());
}
}
bill 450 -> 450
bill 450 -> 405
bill 450 -> 400
fastest: Biryani Box
best: Dosa Hut
(record Restaurant(...) is a short class whose fields are fixed at creation, from episode 3; Restaurant::minutes is a method reference, a short way to say "call minutes() on each item".)
6. Choosing a strategy with a map
Someone still has to pick the strategy from the user's choice (the text "UPI"). Going back to if-else to choose would bring the chain back. Instead, store strategies in a Map from a name to a strategy: choosing is one lookup, and adding a way to pay is one new line.
import java.util.*;
interface PaymentStrategy { int pay(int amount); }
public class Main {
static final Map<String, PaymentStrategy> STRATEGIES = Map.of(
"upi", amount -> amount,
"card", amount -> amount + amount * 2 / 100,
"cod", amount -> amount + 20);
static int checkout(String method, int amount) {
return STRATEGIES.get(method.toLowerCase()).pay(amount); // no if-else chain
}
public static void main(String[] args) {
System.out.println("UPI -> " + checkout("UPI", 450));
System.out.println("card -> " + checkout("card", 450));
System.out.println("gold -> " + checkout("gold coins", 450));
}
}
UPI -> 450
card -> 459
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "PaymentStrategy.pay(int)" because the return value of "java.util.Map.get(Object)" is null
at Main.checkout(Main.java:12)
at Main.main(Main.java:17)
Map.get returns null (no object at all) when the key is missing, and calling a method on null throws NullPointerException. Java's "helpful NPE" message even says which value was null. The fix: check, and fail with a clear message.
import java.util.*;
interface PaymentStrategy { int pay(int amount); }
public class Main {
static final Map<String, PaymentStrategy> STRATEGIES = Map.of(
"upi", amount -> amount,
"card", amount -> amount + amount * 2 / 100,
"cod", amount -> amount + 20);
static int checkout(String method, int amount) {
PaymentStrategy s = STRATEGIES.get(method.toLowerCase());
if (s == null) throw new IllegalArgumentException("We don't accept: " + method);
return s.pay(amount);
}
public static void main(String[] args) {
System.out.println("UPI -> " + checkout("UPI", 450));
System.out.println("card -> " + checkout("card", 450));
try { checkout("gold coins", 450); }
catch (IllegalArgumentException e) { System.out.println("Sorry! " + e.getMessage()); }
}
}
UPI -> 450
card -> 459
Sorry! We don't accept: gold coins
(You could also write Optional.ofNullable(STRATEGIES.get(key)).orElseThrow(...), from episode 5.)
7. The trap: a second abstract method
interface PaymentStrategy {
int pay(int amount);
String name(); // added later by a teammate
}
public class Main {
public static void main(String[] args) {
PaymentStrategy upi = amount -> amount; // a strategy as a lambda
System.out.println(upi.pay(450));
}
}
Main.java:7: error: incompatible types: PaymentStrategy is not a functional interface
PaymentStrategy upi = amount -> amount; // a strategy as a lambda
^
multiple non-overriding abstract methods found in interface PaymentStrategy
1 error
A lambda can fill in only one method. Once the interface has two abstract methods, every lambda written for it stops compiling. Fix: give the extra method a default body (a default method already has code, so it is not abstract):
interface PaymentStrategy {
int pay(int amount);
default String name() { return "payment"; } // default: still ONE abstract method
}
public class Main {
public static void main(String[] args) {
PaymentStrategy upi = amount -> amount; // a strategy as a lambda
System.out.println(upi.pay(450));
}
}
450
With @FunctionalInterface on the interface, the compiler stops the teammate at the interface itself:
Main.java:1: error: Unexpected @FunctionalInterface annotation
@FunctionalInterface
^
PaymentStrategy is not a functional interface
multiple non-overriding abstract methods found in interface PaymentStrategy
1 error
8. When Strategy helps (and when it doesn't)
| Use it when | Skip it when |
|---|---|
| There are many ways to do one job (pay, sort, price, route, compress, validate) | There are two fixed cases that will never change: one small if is simpler |
| The way is chosen at runtime, by the user or the situation | The "algorithms" are one line and never vary |
An if-else / switch chain keeps growing and each branch is a whole algorithm |
Strategy vs Bridge (episode 31): Bridge splits two whole class hierarchies (abstraction and implementation) so both can grow. Strategy swaps one behaviour inside one object. Strategy vs State (next episodes): the structure looks the same, but in State the object switches its own behaviour as its state changes, while in Strategy the client picks the algorithm.
Common mistakes
| Mistake | What you see | Why | Fix |
|---|---|---|---|
| Every algorithm in one if-else | IllegalArgumentException: Unknown payment method: wallet |
A new way means editing the context | One class (or lambda) per strategy |
map.get(name).pay(...) for any input |
NullPointerException: Cannot invoke "PaymentStrategy.pay(int)" because the return value of "java.util.Map.get(Object)" is null |
Unknown key returns null |
Check for null; clear message |
| A second abstract method in the strategy | error: incompatible types: PaymentStrategy is not a functional interface |
A lambda fills only one method | default method; @FunctionalInterface |
Context checks instanceof CardPayment |
No error, but the chain is back | Context depends on concrete strategies | Call only the interface |
| A strategy that keeps state between calls and is shared | Wrong totals in one customer's bill from another's | Shared mutable strategy | Keep strategies stateless, or create one per use |
Mini project: delivery fee strategies
Normal fee: 20 + 5 per km. Rain: add 30. Late night: double. Pick by name.
Solution
import java.util.*;
@FunctionalInterface
interface DeliveryFee { int fee(int distanceKm); }
class FeeCalculator { // context
private DeliveryFee strategy;
FeeCalculator(DeliveryFee strategy) { this.strategy = strategy; }
void setStrategy(DeliveryFee s) { strategy = s; }
int quote(int km) { return strategy.fee(km); }
}
public class Main {
static final Map<String, DeliveryFee> FEES = Map.of(
"normal", km -> 20 + 5 * km,
"rain", km -> 20 + 5 * km + 30, // rain surcharge
"late-night", km -> (20 + 5 * km) * 2); // double after midnight
public static void main(String[] args) {
FeeCalculator calc = new FeeCalculator(FEES.get("normal"));
for (String mode : List.of("normal", "rain", "late-night")) {
calc.setStrategy(FEES.get(mode));
System.out.println(mode + " fee for 4 km: " + calc.quote(4));
}
}
}
normal fee for 4 km: 40
rain fee for 4 km: 70
late-night fee for 4 km: 80
Practice
1. Add NetBankingPayment (fee 10 rupees) without editing Checkout, and sort restaurants by name, then by minutes.
Answer
import java.util.*;
interface PaymentStrategy { int pay(int amount); }
class NetBankingPayment implements PaymentStrategy { // added without editing Checkout
public int pay(int a) { System.out.println("Net banking: paid " + (a + 10) + " (fee 10)"); return a + 10; }
}
class Checkout {
private PaymentStrategy strategy;
Checkout(PaymentStrategy s) { strategy = s; }
int checkout(int amount) { return strategy.pay(amount); }
}
public class Main {
public static void main(String[] args) {
System.out.println("charged: " + new Checkout(new NetBankingPayment()).checkout(450));
record Restaurant(String name, double rating, int minutes) { }
List<Restaurant> list = new ArrayList<>(List.of(new Restaurant("Dosa Hut", 4.6, 40),
new Restaurant("Chai Point", 4.1, 25), new Restaurant("Chai Point", 4.1, 12)));
list.sort(Comparator.comparing(Restaurant::name).thenComparingInt(Restaurant::minutes));
list.forEach(r -> System.out.println(r.name() + " " + r.minutes()));
}
}
Net banking: paid 460 (fee 10)
charged: 460
Chai Point 12
Chai Point 25
Dosa Hut 40
thenComparingInt adds a second sorting strategy that is used only when the first one says two items are equal.
2. Why does Checkout hold a PaymentStrategy field and not a CardPayment field?
Answer
Through the interface it can hold any strategy and swap it. With a CardPayment field it could only ever pay by card: we would be programming to an implementation, not to an interface (episode 7).
3. A switch on a payment-type enum has 12 cases, each 20 lines long. What would you do?
Answer
Turn each case into a concrete strategy and pick one with an EnumMap<PaymentType, PaymentStrategy> (or give each enum constant its own strategy). The switch disappears and each algorithm can be tested alone.
4. Is Comparator.comparingInt(Restaurant::minutes) a strategy? Who is the context?
Answer
Yes: it is one sorting algorithm (compare by minutes) in an object. The context is List.sort (or Collections.sort), which uses the comparator without knowing what it compares.
Quick quiz
class Navigator { // a maps app
RouteStrategy route;
Path find(Place a, Place b) {
return route.plan(a, b);
}
}
// FastestRoute, NoTollRoute, WalkingRoute
// Which one is the CONTEXT?
(a) RouteStrategy (b) Navigator (c) FastestRoute (d) Path
Answer
(b) Navigator. It uses a route strategy without knowing which one. RouteStrategy is the strategy interface; FastestRoute, NoTollRoute and WalkingRoute are concrete strategies.
Interview questions
- What is the Strategy pattern? A behavioural pattern that puts each algorithm of a family in its own class behind a common interface, so the context can use any of them and swap them at runtime.
- What problem does it solve? Growing
if-else/switchchains of algorithms inside one class, which must be edited for every new variant (violating the Open-Closed Principle). - Name the participants. Context, strategy (interface), concrete strategies; the client picks the strategy.
- How do you choose a strategy without if-else? A
Map(orEnumMap) from a key to a strategy, filled once; or dependency injection. - Strategy in the JDK?
ComparatorforList.sort/Collections.sort/TreeMap,FilenameFilter, theFunction/Predicatearguments of streams. - Strategy vs State? Same structure; State changes behaviour from inside as state changes, Strategy is chosen from outside.
- Strategy vs Template Method? Strategy uses composition (swap a whole algorithm object at runtime); Template Method uses inheritance (subclasses fill in steps of a fixed algorithm).
- Strategy vs Bridge? Bridge separates two hierarchies; Strategy swaps one behaviour.
- Downsides? More classes; the client must know the strategies exist to pick one; for tiny algorithms lambdas avoid the class explosion.
- Should strategies hold state? Usually not; stateless strategies can be shared safely (even as singletons or enum constants).
Glossary
| Term | Meaning, with an example |
|---|---|
| Behavioural pattern | A design pattern about how objects share work and communicate. Strategy, Observer, Command |
| Algorithm | A step-by-step way to do a job. "Add 2% and charge the card" |
| Strategy pattern | One algorithm per class behind one interface, swappable. PaymentStrategy |
| Context | The object that uses a strategy without knowing which. Checkout |
| Strategy interface | The common interface all algorithms implement. interface PaymentStrategy { int pay(int amount); } |
| Concrete strategy | One class (or lambda) that implements one algorithm. CardPayment |
| Client | The code that picks a strategy and gives it to the context. Main |
| Swapping algorithms at runtime | Changing the strategy while the program runs. c.setStrategy(new CardPayment()) |
| Runtime | While the program is running (vs compile time) |
| Interchangeable | Any one can replace another without changing the user |
| Encapsulate | Wrap up and hide inside a class |
| Eliminating conditionals | Replacing if-else/switch chains with polymorphic objects |
| Open-Closed Principle | Open for extension, closed for modification (episode 13) |
IllegalArgumentException |
Standard exception for an argument that isn't allowed |
| Functional interface | An interface with exactly one abstract method. Discount |
@FunctionalInterface |
Annotation that makes the compiler check there is only one abstract method |
| Lambda expression | A short way to write that one method. bill -> bill * 90 / 100 |
| Strategies as lambdas | Writing small strategies as lambdas instead of classes |
default method |
An interface method with a body; it isn't abstract |
Comparator |
An object that decides which of two items comes first; a sorting strategy |
| Method reference | Restaurant::minutes: a short way to say "call this method" |
Map |
Key-value storage. Map.of("upi", ..., "card", ...) |
| Strategy selection with a map | Looking up a strategy by name instead of if-else |
null |
"No object at all"; what Map.get returns for a missing key |
NullPointerException |
Thrown when you call a method on null |
| Record | A short class with fixed fields. record Restaurant(String name, double rating, int minutes) |
| Stateless | An object with no fields that change; safe to share. UpiPayment |
| UPI / COD | Unified Payments Interface (India's bank-to-bank phone payments) / cash on delivery |
Summary
- An
if-elsechain of algorithms must be edited for every new variant, and it crashed on "wallet". - Strategy: a strategy interface, one concrete strategy per algorithm, and a context that holds one and can swap it at runtime.
- Small strategies can be lambdas;
Comparatoris Java's own sorting strategy. - Pick strategies with a
Map, and handle a missing key (null). - Keep the strategy interface functional (one abstract method) if you want lambdas; use
@FunctionalInterface.
Next episode: The Observer pattern: tell everyone when something changes.