Implementing the Strategy Pattern using .NET and C#: A Practical Guide

Maximizing Code Reuse and Maintainability with the Strategy Design Pattern in C#

Abdelmajid BACO

--

Photo by Randy Fath on Unsplash

The Strategy design pattern is a behavioral pattern that allows an object to alter its behavior when its internal state changes. This can be useful in situations where an object needs to perform one of several related operations, and the exact operation to be performed depends on the object’s current state.

One way to implement the Strategy pattern in C# is to create an interface that defines the signature of the operation to be performed, and then create a set of concrete classes that implement the interface and provide different implementations of the operation.

For example, let’s say we have a class called PaymentProcessor that handles different types of payments. We could define an interface called IPaymentStrategy that has a single method called ProcessPayment and then create concrete implementations of the interface for each type of payment:

public interface IPaymentStrategy
{
void ProcessPayment(decimal amount);
}

public class CreditCardPaymentStrategy : IPaymentStrategy
{
public void ProcessPayment(decimal amount)
{
Console.WriteLine($"Processing payment of {amount:C} using credit card.");
}
}

public class PayPalPaymentStrategy : IPaymentStrategy
{
public void ProcessPayment(decimal amount)
{
Console.WriteLine($"Processing payment of {amount:C} using PayPal.");
}
}

We can then modify the PaymentProcessor class to have a property of type IPaymentStrategyand a method called SetPaymentStrategy that allows the payment strategy to be changed at runtime:

public class PaymentProcessor
{
private IPaymentStrategy paymentStrategy;

public void SetPaymentStrategy(IPaymentStrategy paymentStrategy)
{
this.paymentStrategy = paymentStrategy;
}

public void ProcessPayment(decimal amount)
{
paymentStrategy.ProcessPayment(amount);
}
}

Now we can create an instance of the PaymentProcessor class and use the SetPaymentStrategy method to change the payment method at runtime:

var paymentProcessor = new PaymentProcessor()…

--

--

Abdelmajid BACO

Senior Full Stack .Net / Angular Developer, Cloud & Azure DevOps, Carrier Manager, Husband, and Father.