Strategy: swapping algorithms
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's finalPrice method has an if-else branch for every coupon, and each new coupon means editing it again. How can you add rules without breaking the old ones?
The problem: one method with a branch per discount rule
ShopLite's finalPrice method has one if-else branch per coupon. Run it and notice how every rule shares one method.
Example 1 · Before: an if-else branch for every coupon
class PriceCalculator { int finalPrice(int amount, String coupon) { int discount; if (coupon.equals("FEST10")) { discount = amount * 10 / 100; } else if (coupon.equals("FLAT200")) { discount = amount >= 999 ? 200 : 0; } else if (coupon.equals("STUDENT")) { discount = Math.min(amount * 15 / 100, 300); } else { discount = 0; } return amount - discount; }}
public class IfElseDiscountDemo { public static void main(String[] args) { PriceCalculator calc = new PriceCalculator(); String[] coupons = {"NONE", "FEST10", "FLAT200", "STUDENT"}; for (String coupon : coupons) { System.out.println(coupon + ": Rs 1499 -> Rs " + calc.finalPrice(1499, coupon) + ", Rs 2999 -> Rs " + calc.finalPrice(2999, coupon)); } }}NONE: Rs 1499 -> Rs 1499, Rs 2999 -> Rs 2999 FEST10: Rs 1499 -> Rs 1350, Rs 2999 -> Rs 2700 FLAT200: Rs 1499 -> Rs 1299, Rs 2999 -> Rs 2799 STUDENT: Rs 1499 -> Rs 1275, Rs 2999 -> Rs 2699
What this code does
- All four rules live in one method. Adding a Diwali coupon means editing it again, next to rules that already work.
- The student cap shows the problem: for Rs 2,999 the 15% would be Rs 449, but the cap limits it to Rs 300. That detail is hidden in the middle of the branch chain.
The method also mixes two jobs: choosing a rule and doing the maths for every rule. You cannot test the student rule on its own, and you cannot reuse it elsewhere, such as in a price preview on the product page.
Strategy interface and concrete strategies
Strategy is a design pattern that puts each way of doing one job in its own class behind a common interface. The code that needs the job holds one of these objects and can swap it for another while the program runs.
A strategy interface names the job once. Each concrete strategy is a small class that does it one way. Below, DiscountStrategy has four implementations.
Example 2 · One class per rule behind DiscountStrategy
interface DiscountStrategy { String name(); int discount(int amount); // rupees off for this amount}
class NoDiscount implements DiscountStrategy { public String name() { return "no coupon"; } public int discount(int amount) { return 0; }}
class PercentOff implements DiscountStrategy { private final int percent;
PercentOff(int percent) { this.percent = percent; }
public String name() { return percent + "% off"; } public int discount(int amount) { return amount * percent / 100; }}
class FlatOff implements DiscountStrategy { private final int off; private final int minAmount;
FlatOff(int off, int minAmount) { this.off = off; this.minAmount = minAmount; }
public String name() { return "Rs " + off + " off above Rs " + minAmount; } public int discount(int amount) { return amount >= minAmount ? off : 0; }}
class StudentDiscount implements DiscountStrategy { public String name() { return "student 15%, max Rs 300"; } public int discount(int amount) { return Math.min(amount * 15 / 100, 300); }}
public class StrategiesDemo { public static void main(String[] args) { DiscountStrategy[] rules = { new NoDiscount(), new PercentOff(10), new FlatOff(200, 999), new StudentDiscount() }; for (DiscountStrategy rule : rules) { System.out.println(rule.name() + ": off Rs " + rule.discount(1499) + " on Rs 1499, Rs " + rule.discount(2999) + " on Rs 2999"); } }}no coupon: off Rs 0 on Rs 1499, Rs 0 on Rs 2999 10% off: off Rs 149 on Rs 1499, Rs 299 on Rs 2999 Rs 200 off above Rs 999: off Rs 200 on Rs 1499, Rs 200 on Rs 2999 student 15%, max Rs 300: off Rs 224 on Rs 1499, Rs 300 on Rs 2999
What this code does
- Each rule is a few lines in its own class.
PercentOffandFlatOfftake their numbers through the constructor, so one class serves many coupons. - The loop treats every rule the same way through the interface. The same objects could power a price preview or a test without any checkout code.
Strategies take settings through their constructors, so one PercentOff class covers 10%, 20% and any other percentage. Each class is short, has one reason to change and can be tested alone.
Three parts to remember: the strategy is the interface (DiscountStrategy), a concrete strategy is one way of doing the job (FlatOff), and the context is the class that uses it (Checkout).
The context holds a strategy and can switch it at runtime
Context is the class that holds a strategy in a field and calls it when it needs the job done. It does not know which concrete strategy it has, so the strategy can be changed while the program runs.
Checkout keeps a DiscountStrategy in a field and calls it. A setter lets other code change the strategy, for example when the shopper applies a coupon.
Example 3 · Checkout switches strategy while the program runs
interface DiscountStrategy { String name(); int discount(int amount);}
class NoDiscount implements DiscountStrategy { public String name() { return "no coupon"; } public int discount(int amount) { return 0; }}
class PercentOff implements DiscountStrategy { private final int percent;
PercentOff(int percent) { this.percent = percent; }
public String name() { return percent + "% off"; } public int discount(int amount) { return amount * percent / 100; }}
class FlatOff implements DiscountStrategy { private final int off; private final int minAmount;
FlatOff(int off, int minAmount) { this.off = off; this.minAmount = minAmount; }
public String name() { return "Rs " + off + " off above Rs " + minAmount; } public int discount(int amount) { return amount >= minAmount ? off : 0; }}
class StudentDiscount implements DiscountStrategy { public String name() { return "student 15%, max Rs 300"; } public int discount(int amount) { return Math.min(amount * 15 / 100, 300); }}
class Checkout { // the context private DiscountStrategy discount = new NoDiscount();
void setDiscount(DiscountStrategy discount) { this.discount = discount; }
String bill(int amount) { int off = discount.discount(amount); return "Rs " + amount + " - Rs " + off + " (" + discount.name() + ") = Rs " + (amount - off); }}
public class SwitchStrategyDemo { public static void main(String[] args) { Checkout checkout = new Checkout(); System.out.println(checkout.bill(1499));
checkout.setDiscount(new PercentOff(10)); // shopper applies FEST10 System.out.println(checkout.bill(1499));
checkout.setDiscount(new StudentDiscount()); // shopper switches to STUDENT System.out.println(checkout.bill(1499)); }}Rs 1499 - Rs 0 (no coupon) = Rs 1499 Rs 1499 - Rs 149 (10% off) = Rs 1350 Rs 1499 - Rs 224 (student 15%, max Rs 300) = Rs 1275
What this code does
Checkoutnever asks which rule it has. It callsdiscount.discount(amount)anddiscount.name(), and the object behind the field decides the answer.- The field starts as
NoDiscount, so the first bill works with no coupon and nonullcheck.
Start the field with a do-nothing strategy, NoDiscount, instead of null. This null object removes every if (discount != null) check, because "no coupon" is just another strategy.
Predict the output
Predict the switch
Read the code, then pick what it prints.
The strategy is swapped between two calls.
null. The first bill then throws NullPointerException. The NoDiscount default prevents it.Choosing a strategy from configuration or user input
Registry is a map from a code or a setting to a strategy object, kept in one place. Input such as FEST10 goes in and a ready-made strategy comes out.
Something must turn a typed coupon code into a strategy object. Keep that choice in one place, Discounts.forCode, backed by a Map.
Example 4 · Choosing from a typed code or a config file
import java.io.IOException;import java.io.StringReader;import java.util.Map;import java.util.Properties;
interface DiscountStrategy { String name(); int discount(int amount);}
class NoDiscount implements DiscountStrategy { public String name() { return "no coupon"; } public int discount(int amount) { return 0; }}
class PercentOff implements DiscountStrategy { private final int percent;
PercentOff(int percent) { this.percent = percent; }
public String name() { return percent + "% off"; } public int discount(int amount) { return amount * percent / 100; }}
class FlatOff implements DiscountStrategy { private final int off; private final int minAmount;
FlatOff(int off, int minAmount) { this.off = off; this.minAmount = minAmount; }
public String name() { return "Rs " + off + " off above Rs " + minAmount; } public int discount(int amount) { return amount >= minAmount ? off : 0; }}
class StudentDiscount implements DiscountStrategy { public String name() { return "student 15%, max Rs 300"; } public int discount(int amount) { return Math.min(amount * 15 / 100, 300); }}
class Checkout { // the context private DiscountStrategy discount = new NoDiscount();
void setDiscount(DiscountStrategy discount) { this.discount = discount; }
String bill(int amount) { int off = discount.discount(amount); return "Rs " + amount + " - Rs " + off + " (" + discount.name() + ") = Rs " + (amount - off); }}
class Discounts { private static final Map<String, DiscountStrategy> BY_CODE = Map.of( "FEST10", new PercentOff(10), "FLAT200", new FlatOff(200, 999), "STUDENT", new StudentDiscount());
static DiscountStrategy forCode(String code) { if (code == null || code.isBlank()) { return new NoDiscount(); } DiscountStrategy strategy = BY_CODE.get(code.trim().toUpperCase()); if (strategy == null) { throw new IllegalArgumentException("Unknown coupon: " + code.trim()); } return strategy; }}
public class ChooseStrategyDemo { public static void main(String[] args) throws IOException { Properties config = new Properties(); config.load(new StringReader("default.discount=FLAT200")); // like a .properties file Checkout checkout = new Checkout(); checkout.setDiscount(Discounts.forCode(config.getProperty("default.discount"))); System.out.println("Default: " + checkout.bill(1499));
String[] typed = {"fest10", " STUDENT ", "", "FREE100"}; // what shoppers typed for (String code : typed) { try { checkout.setDiscount(Discounts.forCode(code)); System.out.println("[" + code + "] " + checkout.bill(1499)); } catch (IllegalArgumentException e) { System.out.println("[" + code + "] " + e.getMessage()); } } }}Default: Rs 1499 - Rs 200 (Rs 200 off above Rs 999) = Rs 1299 [fest10] Rs 1499 - Rs 149 (10% off) = Rs 1350 [ STUDENT ] Rs 1499 - Rs 224 (student 15%, max Rs 300) = Rs 1275 [] Rs 1499 - Rs 0 (no coupon) = Rs 1499 [FREE100] Unknown coupon: FREE100
What this code does
Discounts.forCodeis the only place that knows coupon codes. It cleans the input, sofest10andSTUDENTwork, and it reportsFREE100as unknown instead of silently giving no discount.- The configuration value goes through the same lookup. Checkout receives a ready strategy and never sees the text.
Clean the input first (trim, upper-case) and decide what an unknown code means: an error message, or no discount.
The same lookup works for configuration, such as a default.discount=FLAT200 line in a properties file. The rest of the program never sees the code text, only a DiscountStrategy.
Find the bug
Spot the strategy bug
Each snippet has one wrong line. Tap it, then read the fix.
Shoppers type fest10 in lower case.
Round 1 of 3Strategy and the open/closed principle
The open/closed principle says code should be open for new behaviour but closed for edits to working code. You add a new class instead of changing a class that already works.
A new coupon is a new class. Below, DiwaliDiscount and a BestOf strategy are added while Checkout stays exactly as it was.
Example 5 · Adding a Diwali rule without touching Checkout
import java.util.List;
interface DiscountStrategy { String name(); int discount(int amount);}
class NoDiscount implements DiscountStrategy { public String name() { return "no coupon"; } public int discount(int amount) { return 0; }}
class PercentOff implements DiscountStrategy { private final int percent;
PercentOff(int percent) { this.percent = percent; }
public String name() { return percent + "% off"; } public int discount(int amount) { return amount * percent / 100; }}
class FlatOff implements DiscountStrategy { private final int off; private final int minAmount;
FlatOff(int off, int minAmount) { this.off = off; this.minAmount = minAmount; }
public String name() { return "Rs " + off + " off above Rs " + minAmount; } public int discount(int amount) { return amount >= minAmount ? off : 0; }}
class StudentDiscount implements DiscountStrategy { public String name() { return "student 15%, max Rs 300"; } public int discount(int amount) { return Math.min(amount * 15 / 100, 300); }}
class Checkout { // the context private DiscountStrategy discount = new NoDiscount();
void setDiscount(DiscountStrategy discount) { this.discount = discount; }
String bill(int amount) { int off = discount.discount(amount); return "Rs " + amount + " - Rs " + off + " (" + discount.name() + ") = Rs " + (amount - off); }}
class DiwaliDiscount implements DiscountStrategy { // new rule: a new class public String name() { return "Diwali 25% above Rs 2000"; } public int discount(int amount) { return amount > 2000 ? amount * 25 / 100 : 0; }}
class BestOf implements DiscountStrategy { // a strategy built from strategies private final List<DiscountStrategy> options;
BestOf(List<DiscountStrategy> options) { this.options = options; }
public String name() { return "best offer"; }
public int discount(int amount) { int best = 0; for (DiscountStrategy option : options) { best = Math.max(best, option.discount(amount)); } return best; }}
public class OpenClosedDemo { public static void main(String[] args) { Checkout checkout = new Checkout(); checkout.setDiscount(new DiwaliDiscount()); System.out.println(checkout.bill(2999)); System.out.println(checkout.bill(1499));
checkout.setDiscount(new BestOf(List.of(new DiwaliDiscount(), new FlatOff(200, 999), new StudentDiscount()))); System.out.println(checkout.bill(2999)); System.out.println(checkout.bill(1499)); }}Rs 2999 - Rs 749 (Diwali 25% above Rs 2000) = Rs 2250 Rs 1499 - Rs 0 (Diwali 25% above Rs 2000) = Rs 1499 Rs 2999 - Rs 749 (best offer) = Rs 2250 Rs 1499 - Rs 224 (best offer) = Rs 1275
What this code does
DiwaliDiscountis new code only.Checkoutand the existing strategies were not edited, which is what open/closed means in practice.BestOfis itself a strategy that asks other strategies and keeps the biggest discount. For Rs 2,999 Diwali wins (749); for Rs 1,499 the student rule wins (224).
With Strategy, a new rule is a new class plus one registration line. Checkout, the other strategies and their tests stay untouched.
Strategy is not free. For two fixed rules that never change, a plain if is clearer. Reach for Strategy when rules keep being added, change often or are chosen at runtime. A one-method strategy can also be written as a lambda, which the next lesson covers.
Order of execution
Add the Diwali coupon
Put the steps in the order you would do them.
Next step
Check your understanding
12 quick questions