The Strategy pattern is a behavioral design pattern that allows you to define a family of algorithms, encapsulate each one, and make them interchangeable. This pattern is particularly useful in scenarios where you need to switch between different algorithms at runtime. In this blog, we'll explore how to implement the Strategy pattern in .NET 8.0 using Minimal API with dependency injection.
Real-Time Example Payment Processing System
We'll create a Web API that supports multiple payment methods: Credit Card, PayPal, and Bitcoin. We'll use the Strategy pattern to encapsulate each payment method and switch between them dynamically.
Step-by-Step Implementation
1. Define the Strategy Interface
Create an interface IPaymentStrategy that declares a method ProcessPayment(decimal amount) to standardize the payment processing logic.
public interface IPaymentStrategy
{
void ProcessPayment(decimal amount);
}
2. Implement Concrete Strategies
Implement the IPaymentStrategy interface in classes like CreditCardPaymentStrategy, PayPalPaymentStrategy, and BitcoinPaymentStrategy, each providing specific logic for processing payments.
public class CreditCardPaymentStrategy : IPaymentStrategy
{
public void ProcessPayment(decimal amount)
{
// Implement credit card payment processing logic
Console.WriteLine($"Processing credit card payment of {amount:C}");
}
}
public class PayPalPaymentStrategy : IPaymentStrategy
{
public void ProcessPayment(decimal amount)
{
// Implement PayPal payment processing logic
Console.WriteLine($"Processing PayPal payment of {amount:C}");
}
}
public class BitcoinPaymentStrategy : IPaymentStrategy
{
public void ProcessPayment(decimal amount)
{
// Implement Bitcoin payment processing logic
Console.WriteLine($"Processing Bitcoin payment of {amount:C}");
}
}
3. Create an Interface for the Context
Define an interface IPaymentContext that declares methods SetPaymentStrategy(IPaymentStrategy paymentStrategy) and ExecutePayment(decimal amount) to manage and execute the selected payment strategy.
public interface IPaymentContext
{
void SetPaymentStrategy(IPaymentStrategy paymentStrategy);
void ExecutePayment(decimal amount);
}
4. Implement the PaymentContext Class
Implement the IPaymentContext interface in the PaymentContext class, which stores the current payment strategy and invokes its ProcessPayment method.


MM JAckPosted Jul 17, 2024, 9:56 AM
Well explained