Design Patterns

The Strategy Pattern: Encapsulating Algorithms

Define a family of algorithms, encapsulate each one, and make them interchangeable — open for extension, closed for modification.

February 28, 2026
#strategy-pattern#design-patterns

The Strategy pattern defines a set of interchangeable algorithms behind a common interface. The context class delegates the algorithm to a strategy object rather than hard-coding it. This eliminates conditional branching inside the context and makes it easy to add new algorithms without modifying existing code — satisfying the Open/Closed Principle.

php
interface ShippingStrategy
{
    public function calculate(Order $order): Money;
}

class StandardShipping implements ShippingStrategy { /* ... */ }
class ExpressShipping implements ShippingStrategy { /* ... */ }

class OrderPricer
{
    public function __construct(private readonly ShippingStrategy $shipping) {}

    public function total(Order $order): Money
    {
        return $order->subtotal()->add($this->shipping->calculate($order));
    }
}
Shipping cost strategy

Continue reading