Explain the Strategy pattern.
Topic: design-patterns, Behavioral Patterns. Level: Basic.
Answer
Strategy defines a family of interchangeable algorithms, encapsulates each behind a common interface, and lets the client select one at runtime. It replaces sprawling `if/else`/`switch` on behavior with polymorphism, and follows Open/Closed — add a new strategy without touching existing code. Classic uses: payment methods, sorting/compression algorithms, pricing/discount rules. In Java, a strategy is often just a lambda / functional interface.
```java
interface DiscountStrategy { double apply(double total); }
class NoDiscount implements DiscountStrategy { public double apply(double t){ return t; } }
class PercentOff implements DiscountStrategy {
private final double pct; PercentOff(double p){ pct=p; }
public double apply(double t){ return t * (1 - pct); }
}
class Cart {
private DiscountStrategy strategy = new NoDiscount();
void setStrategy(DiscountStrategy s){ strategy = s; } // swap at runtime
double checkout(double total){ return strategy.apply(total); }
}
Cart cart = new Cart();
cart.setStrategy(new PercentOff(0.10)); // or a lambda: t -> t*0.9
cart.checkout(100); // 90
```