SOLID & Design Patterns Interview Question #23

What is the Strategy Pattern?

SOLID Principles, Design Fundamentals, Repository, Factory, Strategy & Decorator Junior Beginner

Quick Interview Answer

The Strategy Pattern defines a family of interchangeable algorithms behind a common interface. A context delegates a variable piece of behavior to the selected strategy instead of containing a large conditional block.

Detailed Explanation

The Strategy Pattern defines a family of interchangeable algorithms behind a common interface. A context delegates a variable piece of behavior to the selected strategy instead of containing a large conditional block.

Strategy is useful for pricing rules, payment processing, sorting, validation, export formats, or other behavior that varies independently from the caller.

Code Example

public interface IShippingStrategy
{
    decimal Calculate(decimal weight);
}

public class ExpressShipping : IShippingStrategy
{
    public decimal Calculate(decimal weight)
        => 15m + (weight * 2m);
}