Strategy
Define a family of algorithms, encapsulate each one, and make them interchangeable.
There are several ways to do the same job. Sort by price, by rating, by distance. Pay by card, wallet or bank transfer.
Written as one long if/else, the method grows every time you add an option. Each change risks breaking the branches that already worked.
Strategy puts each approach in its own class behind a shared interface. The main code holds one of them and calls it. Adding an option means adding a class, not editing the old ones.
What the interviewer is probing.
1. "What does Strategy replace?" *Probing:* the motivation. *Stalls:* "Classes." *Moves up:* a conditional choosing between algorithms, moved into interchangeable objects selected at runtime.
2. "How is it usually written today?" *Probing:* currency. *Stalls:* "A class per strategy." *Moves up:* often a lambda or function reference, since the interface is frequently single-method — the pattern survives, the ceremony does not.
3. "How do you choose the strategy at runtime?" *Probing:* the practical implementation. *Stalls:* "An if statement." *Moves up:* a map from key to strategy, often populated by injecting all implementations — which keeps adding one from touching existing code.
4. "When is it over-applied?" *Probing:* judgement. *Stalls:* "Never." *Moves up:* when there are two branches that will never grow — an if is clearer than two classes and a factory.
GPS navigation — pick fastest route, shortest route, or avoid tolls. The app delegates to whichever strategy you chose.
Key Concepts
public interface PaymentStrategy {
void pay(double amount);
}
public class CreditCardPayment implements PaymentStrategy {
private final String card;
public CreditCardPayment(String c) { this.card = c; }
public void pay(double amount) { System.out.println("Card: " + amount); }
}
public class ShoppingCart {
private PaymentStrategy strategy;
public void setPaymentStrategy(PaymentStrategy s) { this.strategy = s; }
public void checkout(double total) { strategy.pay(total); }
}