strategy pattern in csharp

The Strategy Pattern is a behavioral design pattern that enables selecting an algorithm at runtime based on the client's choice. It's a great way to achieve separation of concerns and encapsulate behaviors. Here's an example of how to implement it in C#:

main.cs
// Define the context
public class CustomerService
{
    private readonly IShippingStrategy _shippingStrategy;

    public CustomerService(IShippingStrategy shippingStrategy)
    {
        _shippingStrategy = shippingStrategy;
    }

    public decimal CalculateShippingCost(Order order)
    {
        return _shippingStrategy.CalculateShippingCost(order);
    }
}

// Define the interface for strategies
public interface IShippingStrategy
{
    decimal CalculateShippingCost(Order order);
}

// Define concrete strategies
public class USPS : IShippingStrategy
{
    public decimal CalculateShippingCost(Order order)
    {
        // Calculate shipping cost for USPS
    }
}

public class UPS : IShippingStrategy
{
    public decimal CalculateShippingCost(Order order)
    {
        // Calculate shipping cost for UPS
    }
}

// Usage
var order = new Order();
var customerService = new CustomerService(new UPS());
var shippingCost = customerService.CalculateShippingCost(order);
980 chars
44 lines

In this example, CustomerService is the context that uses the IShippingStrategy interface to calculate the shipping cost for an order. The USPS and UPS classes are the concrete implementations of the IShippingStrategy interface that encapsulate the algorithms for calculating shipping cost based on the shipping carrier.

By passing in the desired IShippingStrategy implementation to the CustomerService constructor, the client can select the algorithm at runtime, rather than hard-coding it in the CustomerService class. This allows for greater flexibility and ease of maintenance as different shipping carriers can be added or removed without modifying the CustomerService class.

gistlibby LogSnag