The Strategy pattern encapsulates a family of interchangeable algorithms behind a common interface, letting client code select and swap the algorithm at runtime. This keeps algorithm selection out of conditional logic and out of the classes that use the algorithm.
Key Points: • Algorithms can be switched at runtime without modifying the client that uses them. • Each algorithm lives in its own class, following the single responsibility and open/closed principles. • New strategies can be added without touching existing strategy implementations or client code. • It eliminates long if/else or switch chains for choosing behavior. • Individual strategies are easy to unit test in isolation.
Example: A checkout service might use a DiscountStrategy interface with PercentageDiscount and FlatRateDiscount implementations, letting the application pick the correct strategy based on a customer's membership tier without branching logic scattered through the checkout code.
Interview Tip: A concise interview answer is:
"Strategy lets you encapsulate interchangeable algorithms behind a common interface and swap them at runtime, which removes conditional logic from the client, keeps each algorithm testable in isolation, and makes adding new algorithms a matter of adding a new class rather than editing existing code."