LLD

Behavioral Patterns

Strategy pattern

When one job can be done by several interchangeable rules, give each rule its own class behind one interface, and let the caller pick. We build a checkout's shipping options twice, once with a switch and once with strategies, and look at what each version costs.

An online shop's checkout page shows a few delivery options under the cart: Standard, Express and Same-day, each with its own price. The page asks the same question of every option: "what would you charge for this order?" Each option answers it with completely different rules. Standard looks at weight and delivers free when the order is worth $49 or more. Express charges by zone and weight. Same-day refuses anything outside the city.

Many programs have a job like this, one job with several interchangeable ways of doing it. A ride app calculates fares one way for autos and another for cabs. A payment screen sends money through UPI, a card or net banking. A search page sorts results by price, rating or distance. The caller wants the job done and does not care which rule does it.

The Strategy pattern gives each rule its own class. In this article we build the checkout's shipping options twice. The first version uses a switch on the option. The second uses the Strategy pattern. Then we look at what the pattern costs, how it differs from the State pattern, and how it shows up in interviews.

All the code is Java, and all of it compiles and runs. Every snippet without a Sketch label is cut from a project that compiles: the first-version snippets from the switch version, the rest from the finished design. The Open file button on a finished-design snippet shows the whole file in a code browser.

The checkout we are building

An order is a list of items, each with a price, a weight and a quantity, plus a delivery zone (local, regional or national) and a payment method (prepaid or cash on delivery). The checkout must:

  1. Quote every option that can deliver the order, cheapest first.
  2. Leave out options that cannot deliver it, instead of showing a price that will never be honoured. An option that fails while quoting is left out too, so one broken courier never hides the rest.
  3. Add $3 to every quote when the customer pays cash on delivery.
  4. Calculate the order total for the option the customer picks, and refuse an option that cannot deliver.

The three options have these rules:

OptionCan it deliver?What it charges
StandardAlwaysFree if the order is worth $49 or more. Otherwise $4 for the first 500 g and $2 for each further 500 g or part of it.
ExpressUp to 10 kg$8 local, $12 regional, $18 national, with 1 kg included and $3 for each further kg or part of it.
Same-dayLocal orders up to 5 kg$15 flat.
One order, three options
A $25 dumbbell weighing 2 kg, delivered locally and paid in advance. Standard charges $4 for the first 500 g and $2 for each of three more slabs: $10. Express charges the local $8 plus $3 for the second kilogram: $11. Same-day accepts it because it is local and under 5 kg: $15. The checkout shows the three prices, cheapest first.A $25 dumbbell weighing 2 kg, delivered locally and paid in advance. Standard charges $4 for the first 500 g and $2 for each of three more slabs: $10. Express charges the local $8 plus $3 for the second kilogram: $11. Same-day accepts it because it is local and under 5 kg: $15. The checkout shows the three prices, cheapest first.
Every option answers the same question with its own rules. A $25 dumbbell weighing 2 kg, delivered locally and paid in advance. Standard charges $4 for the first 500 g and $2 for each of three more slabs: $10. Express charges the local $8 plus $3 for the second kilogram: $11. Same-day accepts it because it is local and under 5 kg: $15. The checkout shows the three prices, cheapest first.

The question is the same for every option and the rules behind it are different. That is the shape the Strategy pattern fits. When you meet this in an interview, write the table of options and rules first, as above. Everything after it is about where those rules live in the code.

The first version: a switch on the delivery option

The obvious way to write this is an enum for the options and a switch wherever an option's rule is needed. Here are the two places the checkout needs one, "can it deliver?" and "what does it charge?":

Checkout.javalines 19–50 of 55
    private boolean isAvailable(Order order, DeliveryOption option) {        return switch (option) {            case STANDARD -> true;            case EXPRESS -> order.weightGrams() <= 10_000;            case SAME_DAY -> order.zone() == Zone.LOCAL && order.weightGrams() <= 5_000;        };    }     private int shippingCharge(Order order, DeliveryOption option) {        switch (option) {            case STANDARD -> {                if (order.value() >= 49) {                    return 0;                }                int extraGrams = Math.max(0, order.weightGrams() - 500);                return 4 + (extraGrams + 499) / 500 * 2;            }            case EXPRESS -> {                int base = switch (order.zone()) {                    case LOCAL -> 8;                    case REGIONAL -> 12;                    case NATIONAL -> 18;                };                int extraGrams = Math.max(0, order.weightGrams() - 1000);                return base + (extraGrams + 999) / 1000 * 3;            }            case SAME_DAY -> {                return 15;            }        }        throw new IllegalArgumentException("Unknown option " + option);    }

The rest of the class loops over the enum and calls both methods for each option. This code works, and if the shop will only ever have these three options with these rules, it is a reasonable answer. The trouble starts when the options change.

One option's rules are split across two methods. Same-day's price is on line 46 and its "local only, up to 5 kg" rule is on line 23. Nothing puts them side by side. Someone changing Same-day's weight limit has to know that the other half of its rules is somewhere else.

Every change edits the checkout. A new rate for Express, a free-delivery festival offer, a new courier: each one is an edit to the class that also builds the quotes and adds the cash-on-delivery fee. A new courier also shows how easily the two switches drift apart. Adding PICKUP_POINT to the enum makes the compiler demand a case in isAvailable, because that switch is an expression and must cover every value. The switch in shippingCharge is a statement, so the compiler says nothing. A pickup order then reaches the throw on line 49, and quotes() fails for every order the new option can deliver, which hides every other option's price too.

The rules cannot be tested alone. To check Express's per-kilogram charge, a test has to build a whole checkout and go through it.

Options cannot be switched on and off. If a city has no same-day courier, the only way to hide Same-day there is another if in the checkout.

Where each option's rules live
On the left, the switch version: the colours are the three options, and each one has a stripe in isAvailable() and another in shippingCharge(). On the right, the same six rules regrouped by option: three classes, each outlined in its option's colour. Each class holds both rules for its own option, availability and charge together.On the left, the switch version: the colours are the three options, and each one has a stripe in isAvailable() and another in shippingCharge(). On the right, the same six rules regrouped by option: three classes, each outlined in its option's colour. Each class holds both rules for its own option, availability and charge together.
In the switch version, each option is spread across two methods. With strategies, each option is one class. On the left, the switch version: the colours are the three options, and each one has a stripe in isAvailable() and another in shippingCharge(). On the right, the same six rules regrouped by option: three classes, each outlined in its option's colour. Each class holds both rules for its own option, availability and charge together.

The idea

The Strategy pattern works like this:

  • Each way of doing the job becomes a class. All of them implement one interface, which asks the question every option must answer.
  • The checkout holds a list of these objects, not an enum.
  • To quote an order, the checkout asks each object and collects the answers. It never asks which class it is talking to.
  • The client chooses which object to use. The client is the code outside the context: the code that builds the checkout decides which options exist, and here the customer chooses among them by picking one on the page.
  • The strategy objects keep no data from any one order, only their own constants. So one object of each kind can serve every customer at the same time, and the app creates them once when it starts. demo/RaceCheck.java, near the end, runs sixteen threads against one checkout to show it.

The parts have names. The class that needs the job done, our Checkout, is the context. The interface, ShippingStrategy, is the strategy. The classes that implement it, StandardShipping, ExpressShipping and SameDayShipping, are the concrete strategies.

Building it, step by step

Step 1: one interface for every option

Every option must answer two things: its name for the page, and its charge for an order.

shipping/ShippingStrategy.javalines 7–12 of 12
public interface ShippingStrategy {    String name();     // Empty when this option cannot deliver the order.    OptionalInt chargeFor(Order order);}

chargeFor returns an OptionalInt. A number means "I can deliver this, and here is my price". An empty value means "I cannot deliver this order". The switch version needed two methods for that. Here it is one answer to one question.

Decision

How does an option say it cannot deliver?

A separate isAvailable() method

This is what the switch version did. Every caller must remember to call isAvailable() before chargeFor(), and a caller that forgets gets a price for an order the option cannot deliver. The two methods can also disagree, because nothing ties them together.

Throw an exception from chargeFor()

Exceptions are for mistakes, and "this courier does not go to Pune" is not a mistake. It is an everyday answer. Quoting three options would mean catching an exception for every option that says no.

Return an empty OptionalIntOur pick

Availability and price come back as one answer, so they cannot disagree. A caller that forgets to check gets an exception from getAsInt(), not a wrong price.

Step 2: one class per option

Each option's rules move into its own class. Here is Standard:

shipping/StandardShipping.javalines 7–28 of 28
public class StandardShipping implements ShippingStrategy {    private static final int FREE_ABOVE_VALUE = 49;    private static final int FIRST_SLAB_GRAMS = 500;    private static final int FIRST_SLAB_CHARGE = 4;    private static final int EXTRA_SLAB_GRAMS = 500;    private static final int EXTRA_SLAB_CHARGE = 2;     @Override    public String name() {        return "Standard";    }     @Override    public OptionalInt chargeFor(Order order) {        if (order.value() >= FREE_ABOVE_VALUE) {            return OptionalInt.of(0);        }        int extraGrams = Math.max(0, order.weightGrams() - FIRST_SLAB_GRAMS);        int extraSlabs = (extraGrams + EXTRA_SLAB_GRAMS - 1) / EXTRA_SLAB_GRAMS;        return OptionalInt.of(FIRST_SLAB_CHARGE + extraSlabs * EXTRA_SLAB_CHARGE);    }}

Every number in the rule has a name at the top of the class. The slab calculation on line 25 rounds up, so 501 g counts as two slabs. Standard can always deliver, so it never returns empty.

Same-day shows the real gain. Its two rules, which the switch version kept 23 lines apart, now sit next to each other:

shipping/SameDayShipping.javalines 8–24 of 24
public class SameDayShipping implements ShippingStrategy {    private static final int FLAT_CHARGE = 15;    private static final int MAX_GRAMS = 5_000;     @Override    public String name() {        return "Same-day";    }     @Override    public OptionalInt chargeFor(Order order) {        if (order.zone() != Zone.LOCAL || order.weightGrams() > MAX_GRAMS) {            return OptionalInt.empty();        }        return OptionalInt.of(FLAT_CHARGE);    }}

ExpressShipping follows the same shape, with its zone prices in a map. To change Same-day, you open SameDayShipping.java and nothing else.

Each option can now be tested on its own. A test builds an Order, calls new ExpressShipping().chargeFor(order), and checks the number. It needs no checkout, no cart page and no other option. The edge cases live next to the rule they test: exactly $49 for Standard's free delivery, 501 g for its second slab, 10,001 g for Express's limit.

Decision

What does an option receive?

Only the values it needs

The signature would be chargeFor(weightGrams, zone, orderValue), and each option would see only those three values. But Standard needs the value and the weight, Express needs the weight and the zone, and Same-day needs the zone and the weight. The parameter list is the union of every option's needs, and the next option that needs something new, say the number of items, changes the interface for all of them.

The whole OrderOur pick

The signature is chargeFor(Order order), and each option reads what it needs. An option cannot alter the order: Order is a record, its constructor copies the item list with List.copyOf, and each CartItem is a record too. A new option that needs a new fact about the order reads it from Order, and the interface does not change.

Step 3: the checkout asks every option

The checkout now holds a list of strategies and asks each one:

checkout/Checkout.javalines 18–56 of 86
public class Checkout {    private static final Logger LOG = System.getLogger(Checkout.class.getName());    private static final int CASH_ON_DELIVERY_FEE = 3;     // Keyed by name, read once here, so a quote never calls name() again.    private final Map<String, ShippingStrategy> options;    public List<ShippingQuote> quotes(Order order) {        List<ShippingQuote> quotes = new ArrayList<>();        for (Map.Entry<String, ShippingStrategy> option : options.entrySet()) {            OptionalInt charge;            try {                charge = option.getValue().chargeFor(order);            } catch (RuntimeException e) {                // One courier failing must not hide the others, so skip it and say so in the log.                warn(option.getKey(), e);                continue;            }            if (charge.isPresent()) {                quotes.add(new ShippingQuote(option.getKey(), charge.getAsInt() + cashOnDeliveryFee(order)));            }        }        quotes.sort(Comparator.comparingInt(ShippingQuote::charge));        return quotes;    }

Read lines 41 to 53 again. The checkout never names StandardShipping or any other option. It calls chargeFor on line 44, keeps the options that answered with a price, and adds the cash-on-delivery fee. A new option needs no change here.

Line 54 sorts the quotes cheapest first. Comparator.comparingInt(ShippingQuote::charge) is itself a strategy: sort knows how to sort, and the comparator we pass decides what "smaller" means. Java's standard library uses this idea in many places.

The constructor refuses two mistakes before any customer arrives:

checkout/Checkout.javalines 25–37 of 86
    public Checkout(List<ShippingStrategy> options) {        if (options.isEmpty()) {            throw new IllegalArgumentException("A checkout needs at least one shipping option");        }        Map<String, ShippingStrategy> byName = new LinkedHashMap<>();        for (ShippingStrategy option : options) {            String name = Objects.requireNonNull(option.name(), "shipping option name");            if (byName.putIfAbsent(name, option) != null) {                throw new IllegalArgumentException("Two shipping options are called " + name);            }        }        this.options = Collections.unmodifiableMap(byName);    }

A checkout with no options could never quote anything. Two options with the same name are worse, because the customer picks an option by its name: the second one could never be chosen. Line 31 reads each option's name once and keys the options by it, so the map is the checkout's own copy and a quote never calls name() again. A caller that changes its own list later does not change the checkout.

Decision

Where does the cash-on-delivery fee go?

Inside each option

Each chargeFor adds $3 when the order is cash on delivery. That puts the same rule in every class. When the fee changes to $4, every option must change, and the one that is missed charges the old fee.

In the checkout, after the option answersOur pick

The fee does not depend on the delivery option, so it does not belong in any option. A rule that is the same for every strategy belongs in the context. The options decide what delivery costs, and the checkout adds what the payment method costs.

An option can also fail. A partner courier's rates may come from its own service, and that call can time out. Lines 43 to 49 decide what happens then.

Decision

What happens when one option throws?

Let the exception through

The checkout does nothing special, and the exception leaves quotes(). One courier's slow service then hides every option, including Standard, which never calls anyone. The customer sees an error instead of three good prices.

Skip that option and log itOur pick

The catch on line 45 leaves the failed option out of the list and logs a warning, and the customer chooses from the rest. The logging itself sits in its own try, so a broken logger cannot lose the other quotes either. The cost is that a real bug inside one option, such as a NullPointerException, is also skipped rather than crashing, so somebody has to watch that warning. total() does not catch anything: once the customer has chosen an option, the checkout cannot charge a price it does not have.

Step 4: the customer picks one

The customer sees the quotes and picks an option by name. The checkout finds that option and calculates the total:

checkout/Checkout.javalines 58–73 of 86
    public int total(Order order, String optionName) {        ShippingStrategy option = find(optionName);        OptionalInt charge = option.chargeFor(order);        if (charge.isEmpty()) {            throw new IllegalArgumentException(optionName + " is not available for this order");        }        return Math.addExact(Math.addExact(order.value(), charge.getAsInt()), cashOnDeliveryFee(order));    }     private ShippingStrategy find(String optionName) {        ShippingStrategy option = options.get(optionName);        if (option == null) {            throw new IllegalArgumentException("No shipping option called " + optionName);        }        return option;    }

total asks the option again rather than trusting an earlier quote, and refuses an option that cannot deliver this order. A page that shows only the quoted options never sends one, but the checkout does not rely on that. Line 64 adds with Math.addExact, so a total too big for an int throws instead of turning negative.

The errors fall into two kinds. "Not available for this order" and "No shipping option called …" are for a person: the page shows the message and the customer picks again. A NullPointerException from a missing zone, or an ArithmeticException from an impossible total, means a programmer passed in something that should never happen, and nothing catches them.

In this pattern, the strategy is chosen from outside the context. Here the customer chooses it, at the moment of checkout. The checkout itself never decides which option to use.

The list of options comes from outside, from the code that builds the checkout:

demo/Main.javalines 17–22 of 50
    public static void main(String[] args) {        Checkout checkout = new Checkout(List.of(                new StandardShipping(),                new ExpressShipping(),                new SameDayShipping(),                new PickupPointShipping()));
Decision

Who creates the options?

The checkout, in its constructor

The constructor would run this.options = List.of(new StandardShipping(), new ExpressShipping(), …). This is simple, but the checkout now names every option again, and turning Same-day off in a city without a same-day courier means editing the checkout.

Whoever builds the checkout passes the list inOur pick

The checkout depends only on the interface. The code that starts the app decides which options exist, so a city without same-day delivery gets a checkout built without SameDayShipping. A test can pass in a single option, or a fake one.

Step 5: adding a fourth option

A few months later, the shop adds pickup points: the order goes to a nearby store and the customer collects it, for $2 flat, up to 15 kg. This is the whole change:

shipping/PickupPointShipping.javalines 7–23 of 23
public class PickupPointShipping implements ShippingStrategy {    private static final int FLAT_CHARGE = 2;    private static final int MAX_GRAMS = 15_000;     @Override    public String name() {        return "Pickup point";    }     @Override    public OptionalInt chargeFor(Order order) {        if (order.weightGrams() > MAX_GRAMS) {            return OptionalInt.empty();        }        return OptionalInt.of(FLAT_CHARGE);    }}

Then one more line where the checkout is built, line 22 of Main.java above. Checkout did not change. Neither did Standard, Express or Same-day. In the switch version, the same request meant a new enum value and a new case in both methods of the checkout.

The finished design

The finished design
Checkout uses a list of ShippingStrategy objects, passed in when it is built. The four option classes implement ShippingStrategy. Every option reads the Order it is given; the diagram draws that arrow once, from SameDayShipping, to keep it readable. Checkout reads the Order too, for its payment method. Order is a record made of CartItem records, a Zone and a PaymentMethod. Checkout creates a ShippingQuote record for each option that can deliver.Checkout uses a list of ShippingStrategy objects, passed in when it is built. The four option classes implement ShippingStrategy. Every option reads the Order it is given; the diagram draws that arrow once, from SameDayShipping, to keep it readable. Checkout reads the Order too, for its payment method. Order is a record made of CartItem records, a Zone and a PaymentMethod. Checkout creates a ShippingQuote record for each option that can deliver.
The checkout holds a list of ShippingStrategy objects and never names a concrete one. Checkout uses a list of ShippingStrategy objects, passed in when it is built. The four option classes implement ShippingStrategy. Every option reads the Order it is given; the diagram draws that arrow once, from SameDayShipping, to keep it readable. Checkout reads the Order too, for its payment method. Order is a record made of CartItem records, a Zone and a PaymentMethod. Checkout creates a ShippingQuote record for each option that can deliver.

Here is one checkout, traced through the objects:

One checkout, traced
The customer's page asks for quotes for the local $25 dumbbell (1). Checkout asks each of the four options for its charge (2 to 5). This order suits every option, so each one answers with a price; for an order an option cannot deliver, that option answers empty and is left out. Checkout adds any cash-on-delivery fee, sorts the quotes and returns them (6). The customer picks Same-day (7), and Checkout asks Same-day once more before it adds the price to the order value.The customer's page asks for quotes for the local $25 dumbbell (1). Checkout asks each of the four options for its charge (2 to 5). This order suits every option, so each one answers with a price; for an order an option cannot deliver, that option answers empty and is left out. Checkout adds any cash-on-delivery fee, sorts the quotes and returns them (6). The customer picks Same-day (7), and Checkout asks Same-day once more before it adds the price to the order value.
The checkout asks every option, then the customer picks one. The customer's page asks for quotes for the local $25 dumbbell (1). Checkout asks each of the four options for its charge (2 to 5). This order suits every option, so each one answers with a price; for an order an option cannot deliver, that option answers empty and is left out. Checkout adds any cash-on-delivery fee, sorts the quotes and returns them (6). The customer picks Same-day (7), and Checkout asks Same-day once more before it adds the price to the order value.

The whole project is below. Click any class name in the code to open that class.

checkoutCheckout.java
package checkout; import java.lang.System.Logger;import java.lang.System.Logger.Level;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.OptionalInt; import order.Order;import order.PaymentMethod;import shipping.ShippingStrategy; public class Checkout {    private static final Logger LOG = System.getLogger(Checkout.class.getName());    private static final int CASH_ON_DELIVERY_FEE = 3;     // Keyed by name, read once here, so a quote never calls name() again.    private final Map<String, ShippingStrategy> options;     public Checkout(List<ShippingStrategy> options) {        if (options.isEmpty()) {            throw new IllegalArgumentException("A checkout needs at least one shipping option");        }        Map<String, ShippingStrategy> byName = new LinkedHashMap<>();        for (ShippingStrategy option : options) {            String name = Objects.requireNonNull(option.name(), "shipping option name");            if (byName.putIfAbsent(name, option) != null) {                throw new IllegalArgumentException("Two shipping options are called " + name);            }        }        this.options = Collections.unmodifiableMap(byName);    }     public List<ShippingQuote> quotes(Order order) {        List<ShippingQuote> quotes = new ArrayList<>();        for (Map.Entry<String, ShippingStrategy> option : options.entrySet()) {            OptionalInt charge;            try {                charge = option.getValue().chargeFor(order);            } catch (RuntimeException e) {                // One courier failing must not hide the others, so skip it and say so in the log.                warn(option.getKey(), e);                continue;            }            if (charge.isPresent()) {                quotes.add(new ShippingQuote(option.getKey(), charge.getAsInt() + cashOnDeliveryFee(order)));            }        }        quotes.sort(Comparator.comparingInt(ShippingQuote::charge));        return quotes;    }     public int total(Order order, String optionName) {        ShippingStrategy option = find(optionName);        OptionalInt charge = option.chargeFor(order);        if (charge.isEmpty()) {            throw new IllegalArgumentException(optionName + " is not available for this order");        }        return Math.addExact(Math.addExact(order.value(), charge.getAsInt()), cashOnDeliveryFee(order));    }     private ShippingStrategy find(String optionName) {        ShippingStrategy option = options.get(optionName);        if (option == null) {            throw new IllegalArgumentException("No shipping option called " + optionName);        }        return option;    }     private int cashOnDeliveryFee(Order order) {        return order.paymentMethod() == PaymentMethod.CASH_ON_DELIVERY ? CASH_ON_DELIVERY_FEE : 0;    }     private static void warn(String optionName, RuntimeException cause) {        try {            LOG.log(Level.WARNING, optionName + " could not quote", cause);        } catch (RuntimeException ignored) {            // A broken logger must not cost the customer the other quotes.        }    }}
Click a class name in the code to open its fileJava · 86 lines · 375 in the project

The demo in demo/Main.java builds a checkout with all four options and runs two orders through it:

$ java demo.Main
Order 1: $62, 1.0 kg, REGIONAL, CASH_ON_DELIVERY
  Standard      $3
  Pickup point  $5
  Express       $15
  chose Express, total $77
  tried Same-day: Same-day is not available for this order

Order 2: $25, 2.0 kg, LOCAL, PREPAID
  Pickup point  $2
  Standard      $10
  Express       $11
  Same-day      $15
  chose Same-day, total $40

The first order is worth $62 and goes to a regional address, cash on delivery. Standard is free because the order is over $49, so its quote is just the $3 cash-on-delivery fee. Express charges the regional $12 plus $3. Same-day is missing from the list, because it only delivers locally, and choosing it anyway is refused. The second order is a $25 dumbbell, local and prepaid. All four options can deliver it, and the prices match the figure at the top of the article, with the new pickup option first at $2.

The options keep no data from any one order, so one checkout can serve many customers at once. demo/RaceCheck.java checks this. It quotes 100 different orders alone, then quotes each of them 100 times more from 16 threads sharing one checkout, and compares every answer with the one it got alone:

$ java demo.RaceCheck
10000 quotes from 16 threads on one checkout, 0 different from the single-threaded answer

What it costs

The pattern makes one kind of change cheap and another kind expensive.

Adding an option is cheap. It is one new class and one line where the checkout is built, as Step 5 showed. No existing option changes, and neither does the checkout.

Changing the question is expensive. Suppose the page must also show "arrives in 2 to 4 days" under each option. That is a new method on ShippingStrategy, say estimatedDays(Order order), and every option class must implement it. In the switch version it is one new method in one class.

Which change is cheap
Classes are white and the interface is purple, as in the class diagram. An amber outline marks each box the change touches. On the left, adding the pickup option touches one new class and one line in Main, and the checkout, the interface and the other options stay as they are. On the right, adding an estimatedDays() question touches the interface, all four option classes and the Checkout, which now shows the estimate.Classes are white and the interface is purple, as in the class diagram. An amber outline marks each box the change touches. On the left, adding the pickup option touches one new class and one line in Main, and the checkout, the interface and the other options stay as they are. On the right, adding an estimatedDays() question touches the interface, all four option classes and the Checkout, which now shows the estimate.
A new option is a new class. A new question touches every class. Classes are white and the interface is purple, as in the class diagram. An amber outline marks each box the change touches. On the left, adding the pickup option touches one new class and one line in Main, and the checkout, the interface and the other options stay as they are. On the right, adding an estimatedDays() question touches the interface, all four option classes and the Checkout, which now shows the estimate.

So the question to ask is the same as for most patterns: which way will this code grow? Shipping options, fare rules, payment methods and discount rules gain new members far more often than they gain new questions. That is where Strategy pays off.

There are smaller costs. Three branches in one file become an interface and three classes, five files counting the checkout, and reading one option's quote means opening its class. A reader new to the code has to find where the list of options is built to know which options exist.

When the pattern is too much

If two options differ only in their numbers, not in their logic, they are one class with different data. Suppose the shop adds "Express Plus", which is Express with different zone prices. That is not a new class. It is a second ExpressShipping object built with a different price table:

Sketchnot part of the final code
public ExpressShipping(String name, Map<Zone, Integer> baseCharge, int extraKgCharge) {    this.name = name;    this.baseCharge = Map.copyOf(baseCharge);    this.extraKgCharge = extraKgCharge;}

A strategy class is worth writing when the rule is different, the way Same-day's "local only" is a different rule from Standard's weight slabs.

And if the strategy has a single method, Java does not need a named class for it at all. Any interface with one abstract method can take a lambda, which is exactly what Comparator.comparingInt builds on line 54:

Sketchnot part of the final code
Comparator<ShippingQuote> byCharge = (first, second) -> Integer.compare(first.charge(), second.charge());quotes.sort(byCharge);

Our ShippingStrategy has two methods, a name and a charge, so each option is a class. That also gives each option a place for its constants and a file of its own.

We would not use the pattern in two more cases:

  • Two fixed rules. If there will only ever be "prepaid" and "cash on delivery", an if is clearer than an interface and two classes.
  • An interface with one implementation, "in case we need another". That is extra code for a change that may never come. Write the interface when the second rule arrives.

Strategy or State?

The two class diagrams look the same: a class holds a reference to an interface, and several classes implement it. The State pattern page builds a vending machine with it. The difference is who chooses the object, and when.

StrategyState
Who picks the objectThe client, from outside: the code that builds the context, or here the customerThe objects themselves, as things happen
Does it change by itselfNo. It changes only when someone outside picks anotherYes. After a coin, the machine is in a new state
Do the implementations know each otherNo. Each option stands aloneOften: each state usually creates the next one
ExampleShipping options, fare rules, sort ordersVending machine: Idle, Has money, Sold out

A short way to say it: with Strategy, the client chooses how the work is done. With State, the object's own history chooses.

In an interview

Strategy fits wherever a rule can vary in a low-level design: fees and fares, payment methods, discounts, sorting and ranking, retry and back-off policies, and how a spot or a seat is chosen. The Parking Lot design uses it twice, once for choosing a spot and once for the parking fee. The pattern answers the question "and what if the business wants a different rule?"

One follow-up to prepare for is "pick the cheapest option for the customer by default". This needs no new pattern. The checkout already sorts by charge, so the default is the first quote. "Pick the fastest option" is harder, because nothing in the design knows delivery times yet. It first needs the estimatedDays() question from What it costs, which touches every option. After that, the sort order becomes a parameter, a Comparator passed into the checkout, which is a strategy again.

Present it in this order:

  1. Write the table of options and rules first. The interviewer sees that you understood the rules before you design anything.
  2. Name the one question every option answers, and write the interface. Say what "cannot do it" looks like.
  3. Write the context and one or two concrete strategies in full. Then say what a new option costs: one class and one line.

Mistakes to avoid:

  • A factory with the same switch inside it. Moving the switch from the checkout into a ShippingFactory.create(option) changes nothing if every new option still edits that switch. Let the code that builds the checkout pass in the list.
  • Rules that apply to every strategy, copied into each one. The cash-on-delivery fee belongs in the context.
  • A strategy that stores data from one request. Our options keep only constants, so one object can serve every customer at once. An option that saved the last order in a field would mix up two customers checking out together.
  • A new class for a new number. Express and Express Plus are one class with two price tables.
  • Strategies that call each other. If one option needs to know what another charged, the rules are not interchangeable, and Strategy is the wrong pattern.

Summary

  • Use Strategy when one job has several interchangeable rules, and new rules keep arriving.
  • Write the table of options and rules first. Then find the one question every option answers.
  • The context holds a list of strategies, asks them, and never names a concrete one. The client chooses.
  • Rules that are the same for every strategy stay in the context.
  • Adding a strategy is cheap. Changing the question touches every strategy.
  • If two strategies differ only in numbers, make them one class with different data.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.