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.
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.
- 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.
- 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.
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.
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.
// 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.
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 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.
- 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.
- 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.
- 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.
- • 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.
- "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."