The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. It lets the algorithm vary independently from the clients that use it. This is the #1 tool for eliminating 100-line if/else blocks used for selecting logic.
A user can pay via CreditCard, PayPal, or Bitcoin. Instead of one giant Process() method, you create three Strategy classes.
public interface IPaymentStrategy
{
void Pay(decimal amount);
}
// THE CLIENT (Context)
public class CheckoutProcess
{
private IPaymentStrategy _strategy;
public void SetStrategy(IPaymentStrategy s) => _strategy = s;
public void Checkout(decimal amount) => _strategy.Pay(amount);
}
It follows the Open/Closed Principle. Next year, when the marketing team wants to add "Pay with Reward Points," you don't edit your existing checkout logic. You just create a new RewardPointStrategy class. The core system remains stable and untouched.
Q: "How is the Strategy pattern different from Dependency Injection?"
Architect Answer: "They are highly complementary. **Dependency Injection** is the *Mechanism* we use to get the strategy into the class. The **Strategy Pattern** is the *Architectural Design* of having multiple swappable implementations of an interface to handle different business rules. Strategy defines the 'Shape' of the solution; DI is the 'Plumbing' that connects it."