PHP › Design Patterns in PHP

How does the Strategy pattern let you define a family of interchangeable algorithms and select one at runtime?

Intermediate

Answer

The Strategy pattern defines a common interface for a family of related algorithms, letting you encapsulate each specific algorithm as its own separate class, and the code using these algorithms depends only on the shared interface, meaning you can swap which specific strategy is used at runtime without modifying the code that relies on it, which is especially useful for things like different discount calculation methods or different sorting approaches.
interface DiscountStrategy {
    public function calculate(float $total): float;
}
class PercentageDiscount implements DiscountStrategy {
    public function calculate(float $total): float { return $total * 0.9; }
}
Real-world example An e commerce checkout system uses the Strategy pattern to apply different discount calculation strategies, such as a percentage discount or a flat amount discount, selecting the appropriate strategy at checkout time based on the specific promotion currently active.

Common follow-ups: How does the Strategy pattern differ from simply using a series of if else statements?;How would you inject the correct strategy into a class using dependency injection?