LOW-LEVEL DESIGN · BEHAVIORAL PATTERNS · BEHAVIORAL · 34 OF 48

Strategy Pattern in Java: Swap Algorithms at Runtime, With Lambdas

The Strategy pattern through ride fares: metered, airport and night rules behind one FareRule interface, a TripBilling context that swaps them at runtime, lambdas as strategies, a picker that chooses, Strategy vs State and Template Method, Comparator and RejectedExecutionHandler, and its use in parking lot, rate limiter and splitwise designs.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 16

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 117 lines, with a small main() demo. Save it as RideFareStrategyDemo.java, then run javac RideFareStrategyDemo.java && java RideFareStrategyDemo.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * Strategy: each fare formula is its own FareRule; TripBilling holds one and can swap it at runtime.
 * Problem first (one switch over mode strings), then the strategies, the context, a lambda and a picker.
 */
public class RideFareStrategyDemo {

    record Trip(String id, int metres, int minutes, int startHour, boolean toAirport) {}

    record Receipt(String tripId, long paise) {
        String show() { return String.format("%s  Rs %d.%02d", tripId, paise / 100, paise % 100); }
    }

    // ---------- the problem: every formula in one switch over a string ----------
    static long fareTheHardWay(String mode, Trip t) {
        return switch (mode) {
            case "METERED" -> 5000 + t.metres() * 12L / 10 + t.minutes() * 150L;
            case "AIRPORT" -> 65_000;
            case "NIGHT" -> (5000 + t.metres() * 12L / 10 + t.minutes() * 150L) * 5 / 4;   // copy-pasted
            default -> throw new IllegalArgumentException("unknown mode " + mode);         // typos fail late
        };
    }

    // ---------- the strategy interface and three concrete strategies ----------
    /** One method, so it is also a functional interface: a lambda can be a FareRule. */
    interface FareRule {
        long paise(Trip trip);
    }

    /** Fifty rupees base, twelve rupees per km, one rupee fifty per minute. Money is in paise. */
    static final class MeteredFare implements FareRule {
        @Override
        public long paise(Trip t) { return 5000 + t.metres() * 12L / 10 + t.minutes() * 150L; }
    }

    static final class AirportFlatFare implements FareRule {
        private final long flatPaise;

        AirportFlatFare(long flatPaise) { this.flatPaise = flatPaise; }

        @Override
        public long paise(Trip t) { return flatPaise; }
    }

    /** Twenty five percent on top of the metered fare. It reuses MeteredFare instead of copying it. */
    static final class NightFare implements FareRule {
        private final FareRule base = new MeteredFare();

        @Override
        public long paise(Trip t) { return base.paise(t) * 5 / 4; }
    }

    // ---------- the context: knows only the interface ----------
    static final class TripBilling {
        private FareRule rule;

        TripBilling(FareRule rule) { this.rule = rule; }

        /** Swap the algorithm at runtime. */
        void use(FareRule next) { this.rule = next; }

        Receipt bill(Trip t) { return new Receipt(t.id(), rule.paise(t)); }
    }

    // ---------- choosing lives in one place, apart from the formulas ----------
    static final class FareRulePicker {
        private final FareRule metered = new MeteredFare();
        private final FareRule airport = new AirportFlatFare(65_000);
        private final FareRule night = new NightFare();

        FareRule pick(Trip t) {
            if (t.toAirport()) return airport;
            int h = t.startHour();
            if (h >= 22 || h < 6) return night;
            return metered;
        }
    }

    public static void main(String[] args) {
        Trip t1 = new Trip("T1", 8_000, 25, 10, false);    // city ride in the morning
        Trip t2 = new Trip("T2", 8_000, 25, 23, false);    // same ride at eleven at night
        Trip t3 = new Trip("T3", 31_000, 55, 14, true);    // to the airport
        List<Trip> trips = List.of(t1, t2, t3);

        System.out.println("Before: one switch over strings");
        System.out.println("  T1 metered: " + fareTheHardWay("METERED", t1) + " paise");
        try {
            fareTheHardWay("METERD", t1);
        } catch (IllegalArgumentException e) {
            System.out.println("  a typo is only caught at runtime: " + e.getMessage());
        }

        System.out.println("After: the picker chooses, TripBilling just calls the rule");
        FareRulePicker picker = new FareRulePicker();
        TripBilling billing = new TripBilling(new MeteredFare());
        for (Trip t : trips) {
            FareRule rule = picker.pick(t);
            billing.use(rule);
            System.out.println("  " + billing.bill(t).show() + "  via " + rule.getClass().getSimpleName());
        }

        System.out.println("A lambda is a strategy too: festival cap of 300 rupees");
        FareRule metered = new MeteredFare();
        FareRule festival = trip -> Math.min(metered.paise(trip), 30_000);
        billing.use(festival);
        System.out.println("  " + billing.bill(t3).show() + "  (metered would be "
                + metered.paise(t3) / 100 + " rupees)");

        System.out.println("Comparator is the strategy you already use");
        List<Trip> byFare = new ArrayList<>(trips);
        byFare.sort(Comparator.comparingLong((Trip t) -> picker.pick(t).paise(t)).reversed());
        byFare.forEach(t -> System.out.println("  " + t.id() + " " + picker.pick(t).paise(t) + " paise"));
    }
}

Notes

The problem

Here is the naive billing code. One method takes a mode string and switches over it: metered, airport, night. Each branch holds a different formula. Adding a festival fare means opening this class again, and a mistake in one branch can break the others. You cannot test the airport rule on its own, and a typo in a mode string only fails at runtime. The class changes for every pricing idea anyone has.

All rules in one place
long fare(String mode, Trip t) {
  return switch (mode) {
    case "METERED" -> 5000
        + t.metres() * 12L / 10
        + t.minutes() * 150L;
    case "AIRPORT" -> 65_000;
    case "NIGHT" -> ...;
    // FESTIVAL goes here, again
    default -> throw ...;
  };
}

The idea

The idea in one sentence: put each way of doing a job in its own class, behind one shared interface, and let the caller choose which one to use. The class that needs the job done, called the context, holds one strategy object and simply calls it. To change the behaviour, you hand it a different strategy. The context code never changes. This is the open closed principle in action: open to new fare rules, closed to edits.

Strategy in plain words
  • a family of interchangeable
  • algorithms, each in its own
  • class, behind one interface
  • the context holds ONE of
  • them and calls it
  • swap the object to change
  • the behaviour; the context
  • code stays the same

The structure

The participants. The strategy interface is FareRule, with one method that takes a trip and returns the fare in paise. Each concrete strategy is one formula: MeteredFare, AirportFlatFare and NightFare. The context is TripBilling, which holds one FareRule and uses it to build a receipt. The client, RideApp, decides which rule applies. TripBilling depends only on the interface, never on a concrete class.

Participants
  • strategy: FareRule
  • long paise(Trip trip)
  • concrete strategies:
  • MeteredFare
  • AirportFlatFare
  • NightFare
  • context: TripBilling
  • holds one FareRule
  • client: RideApp
  • decides which rule

Code: the strategies

In code, FareRule has a single method, paise, that takes a trip. MeteredFare charges a base of fifty rupees, twelve rupees per kilometre and one rupee fifty per minute. Money is a long number of paise, never a double, so rounding never loses money. AirportFlatFare just returns six hundred and fifty rupees. Each rule can now be unit tested on its own, with a handful of sample trips.

FareRule and MeteredFare
interface FareRule {
  long paise(Trip trip);
}

final class MeteredFare
    implements FareRule {
  public long paise(Trip t) {
    return 5000 + t.metres() * 12L / 10
        + t.minutes() * 150L;
  }
}

Code: the context

TripBilling receives its rule through the constructor, and a small method called use lets you swap it at runtime. The bill method asks the current rule for the fare and builds a receipt. It has no if statements about trip types at all. Rounding, tax or the receipt format can change in TripBilling without touching any fare formula, and a new formula never touches TripBilling.

TripBilling
final class TripBilling {
  private FareRule rule;
  TripBilling(FareRule rule) {
    this.rule = rule;
  }
  void use(FareRule next) { rule = next; }
  Receipt bill(Trip t) {
    long p = rule.paise(t);
    return new Receipt(t.id(), p);
  }
}

Run-through

Follow it at runtime. Trip T two starts at eleven at night, so the app gives TripBilling the night rule and calls bill. TripBilling asks NightFare for the fare and gets two hundred and twenty nine rupees thirty seven. Trip T three ends at the airport, so the app swaps in the airport rule and bills again: six hundred and fifty rupees. Same TripBilling object, same bill method, a different answer, because a different strategy is plugged in.

Lambdas as strategies

Since Java eight, a strategy interface with one method is a functional interface, so a lambda can be a strategy. A festival offer that caps the metered fare at three hundred rupees is one line, with no new class file. Use lambdas for small, short lived rules, and full classes when a rule has its own fields, needs a clear name in logs, or deserves its own tests. You can also reuse standard interfaces like Function or Comparator instead of declaring your own.

A strategy in one line
// FareRule has one abstract method,
// so a lambda is a FareRule
FareRule festival = trip ->
    Math.min(metered.paise(trip),
             30_000);

billing.use(festival);

FareRule halfOff = trip ->
    metered.paise(trip) / 2;

Choosing a strategy

Something still has to decide which rule applies. Put that choice in one place: a small FareRulePicker, or a map from trip kind to rule built at start up. Airport trips get the flat fare, trips that start between ten at night and six in the morning get the night fare, and everything else is metered. The if statements did not disappear, but now they only choose. They no longer calculate, and each formula lives alone.

FareRulePicker
FareRule pick(Trip t) {
  if (t.toAirport()) return airport;
  int h = t.startHour();
  if (h >= 22 || h < 6) return night;
  return metered;
}

// or a Map<TripKind, FareRule>
// built once at start-up

When to use it

Use Strategy when there are several ways to do the same job, when the choice depends on runtime data or on the customer, when rules change often, or when you want to test each rule alone. Skip it when there are two fixed options that never change. A single if statement is easier to read than an interface, two classes and a picker. The cost of the pattern is more small types, so it should buy you real flexibility.

Use it or skip it
  • use it when:
  • • several ways to do one job
  • • the choice changes at
  • runtime or per customer
  • • the rules change often
  • • each rule needs its own tests
  • skip it when:
  • • two fixed options that
  • never change: an if is
  • clearer

Already in Java

Java is full of strategies. A Comparator is a sorting strategy: the sort method stays the same, and you pass by distance or by fare to change the order. ThreadPoolExecutor takes a RejectedExecutionHandler strategy that decides what happens when it cannot accept a task, such as abort or caller runs. In Spring, you can inject a map of every bean that implements one interface, keyed by bean name, and pick a strategy from it.

Strategies you know
  • Comparator: how to order
  • trips.sort(byDistance)
  • trips.sort(byFare)
  • ThreadPoolExecutor takes a
  • RejectedExecutionHandler:
  • AbortPolicy, CallerRunsPolicy
  • Spring: inject a Map of all
  • beans of one interface,
  • keyed by bean name

Strategy vs State

Strategy and State have the same class diagram, which is why interviewers love asking about them. With Strategy, the client chooses the algorithm from outside, and strategies know nothing about each other. With State, the object moves between states as events happen, and each state decides what comes next. A fare rule chosen per trip is a strategy. A vending machine moving from idle, to has coin, to dispensing is state.

Same shape, different driver
  • Strategy:
  • the client picks the
  • algorithm; strategies do
  • not know each other
  • State:
  • the object changes its own
  • behaviour as events happen;
  • each state picks the next
  • fare rule: Strategy
  • vending machine: State

Other neighbours

Two more neighbours. Template Method fixes the steps of an algorithm in a base class and lets subclasses fill in one step. That is inheritance, and the choice is made when you write the subclass. Strategy puts the whole algorithm in a separate object. That is composition, so you can swap it while the program runs. A Command is also an object with one method, but it represents an action to run later, not a way to calculate something.

Strategy vs the rest
  • Template Method:
  • fixed steps in a base class,
  • subclasses fill in a step;
  • inheritance, fixed early
  • Strategy:
  • the whole algorithm is a
  • separate object; composition,
  • swappable at runtime
  • Command: an action to run
  • later, not a way to compute

In LLD interviews

Strategy is the most used pattern in machine coding rounds. A parking lot has a pricing strategy and a spot choosing strategy. A rate limiter offers token bucket, sliding window and fixed window algorithms behind one RateLimiter interface. An expense splitter supports equal, exact and percent splits. An elevator system picks which car answers a call. The common mistake is adding the interface but keeping a switch on type inside the context anyway.

Where it shows up
  • • parking lot: PricingStrategy,
  • SpotStrategy
  • • rate limiter: token bucket,
  • sliding window, fixed window
  • • expense splitter: equal,
  • exact, percent splits
  • • elevator: which car answers
  • • payments: card, UPI, wallet
  • mistake: a switch left in
  • the context anyway

Say it like this

How to say it. Fare calculation is a FareRule strategy. Metered, airport and night rules are separate classes, a picker chooses one per trip, and TripBilling just calls whichever rule it is given. A new rule is a new class or a lambda, with no edits to billing, and each rule has its own unit tests. Then add that spot choice or a rate limiting algorithm would be designed the same way.

In the interview
  • "Fare calculation is a
  • FareRule strategy. Metered,
  • airport and night rules are
  • separate classes; a picker
  • chooses one per trip, and
  • TripBilling just calls it.
  • A new rule is a new class or
  • a lambda, with no edits to
  • billing."

Interview questions

What is the Strategy pattern?

Strategy defines a family of interchangeable algorithms, puts each one in its own class behind a common interface, and lets a context object use whichever one it is given. The behaviour can change at runtime by swapping the strategy object, without editing the context.

What is the difference between Strategy and State?

They share a structure, but Strategy is chosen from outside by the client and strategies do not know each other. In State, the object changes its own state as events happen, and state objects usually decide the next state. Strategy answers how to do something; State answers what to do in the current situation.

Can a lambda be used as a strategy in Java?

Yes. If the strategy interface has a single abstract method, it is a functional interface, so a lambda or method reference can implement it. Lambdas suit small rules; named classes are better when a rule has fields, needs a clear name or has its own tests.

How do you choose which strategy to use?

Keep the selection in one place, separate from the algorithms: a small picker or factory with the rules, or a Map from a key such as an enum to the strategy, built at start-up. In Spring you can inject a Map of all beans implementing the interface, keyed by bean name.

How is Strategy different from Template Method?

Template Method uses inheritance: a base class fixes the steps and subclasses override some of them, so the choice is fixed at compile time. Strategy uses composition: the whole algorithm is a separate object that can be replaced at runtime.

Which SOLID principle does the Strategy pattern support?

Mainly the open/closed principle: new behaviour is added as a new strategy class without modifying the context. It also supports single responsibility, since each algorithm lives in its own class, and dependency inversion, since the context depends on an interface.

Give examples of the Strategy pattern in the Java standard library.

Comparator is a sorting strategy passed to List.sort and Collections.sort. ThreadPoolExecutor accepts a RejectedExecutionHandler such as AbortPolicy or CallerRunsPolicy to decide what happens when a task cannot be accepted.

Where would you use Strategy in a parking lot or rate limiter design?

In a parking lot, pricing (hourly, flat, weekend) and spot selection (best fit, nearest to lift) are separate strategy interfaces. In a rate limiter, token bucket, fixed window and sliding window algorithms implement one RateLimiter interface so the algorithm can be chosen per client or endpoint.