Strategy Pattern: Interchangeable Algorithms
Strategy Pattern: Interchangeable Algorithms
The Strategy Pattern is a behavioral design pattern that lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable.
🏗️ The Problem
Imagine you are building a payment system. Initially, you only support Credit Card payments. Later, you need to add PayPal and Google Pay. Without the Strategy pattern, your code would be filled with if-else or switch statements, making it hard to maintain and extend.
🚀 The .NET Implementation
In .NET, the Strategy pattern is often implemented using interfaces and dependency injection.
1. The Strategy Interface
public interface IPaymentStrategy
{
void Pay(decimal amount);
}2. Concrete Strategies
public class CreditCardPayment : IPaymentStrategy
{
public void Pay(decimal amount)
{
Console.WriteLine($"Paying {amount:C} using Credit Card.");
}
}
public class PayPalPayment : IPaymentStrategy
{
public void Pay(decimal amount)
{
Console.WriteLine($"Paying {amount:C} using PayPal.");
}
}3. The Context (Payment Processor)
public class PaymentContext
{
private IPaymentStrategy _paymentStrategy;
public void SetPaymentStrategy(IPaymentStrategy strategy)
{
_paymentStrategy = strategy;
}
public void ProcessPayment(decimal amount)
{
_paymentStrategy.Pay(amount);
}
}🛠️ Real-World Usage (Client)
var context = new PaymentContext();
// Pay with Credit Card
context.SetPaymentStrategy(new CreditCardPayment());
context.ProcessPayment(100.00m);
// Change to PayPal dynamically
context.SetPaymentStrategy(new PayPalPayment());
context.ProcessPayment(50.00m);💡 Why use Strategy?
- OCP (Open/Closed Principle): You can add new payment methods without changing existing code.
- Testing: You can easily mock different strategies for unit testing.
- Runtime Flexibility: Switch algorithms on the fly based on user choice or environment.