The Strategy pattern is a behavioral pattern that encapsulates a family of interchangeable algorithms behind a common interface, letting the algorithm vary independently from the code that uses it. It's used whenever a task can be done multiple ways and you want to switch between those ways without touching the calling code.
Key Points: • Each algorithm variant is implemented as a separate class behind a shared interface. • The client holds a reference to the interface and can be configured with any concrete strategy. • It removes long if/else or switch blocks that pick behavior based on a type flag. • New algorithms can be added by creating a new class, without modifying existing code. • Common uses include sorting comparators, payment processing methods, and pricing/discount rules.
Example: An e-commerce checkout can use a DiscountStrategy interface with PercentageDiscount and FlatDiscount implementations, letting the order total be calculated the same way regardless of which discount type is active.
Code Example:
interface DiscountStrategy {
double apply(double price);
}
class PercentageDiscount implements DiscountStrategy {
public double apply(double price) { return price * 0.9; }
}
class NoDiscount implements DiscountStrategy {
public double apply(double price) { return price; }
}Interview Tip: A concise interview answer is:
"Strategy lets you encapsulate a family of algorithms behind one interface and swap between them at runtime without changing the client code. I'd use it any time there's more than one way to do something, like sorting, pricing, or payment processing, and I want to avoid a big conditional block picking the behavior."