What is the Strategy pattern

The Strategy pattern is a behavioral design pattern that enables selecting an algorithm's behavior at runtime. It defines a family of algorithms, encapsulates each one, and makes them interchangeable. This allows a client to choose an algorithm from a family of algorithms without altering the code that uses the algorithm.

This pattern is useful when you have multiple algorithms for a specific task, and you want to switch between them dynamically, promoting the Open/Closed Principle by preventing modifications to the code when introducing new algorithms.

Here’s a simple example of the Strategy pattern implemented in PHP:

<?php // Strategy interface interface Strategy { public function execute(int $a, int $b): int; } // Concrete Strategy A class Addition implements Strategy { public function execute(int $a, int $b): int { return $a + $b; } } // Concrete Strategy B class Subtraction implements Strategy { public function execute(int $a, int $b): int { return $a - $b; } } // Context class Calculator { private $strategy; public function __construct(Strategy $strategy) { $this->strategy = $strategy; } public function setStrategy(Strategy $strategy) { $this->strategy = $strategy; } public function calculate(int $a, int $b): int { return $this->strategy->execute($a, $b); } } // Client code $calculator = new Calculator(new Addition()); echo $calculator->calculate(5, 3); // Output: 8 $calculator->setStrategy(new Subtraction()); echo $calculator->calculate(5, 3); // Output: 2 ?>

Strategy pattern behavioral design pattern algorithm encapsulation Open/Closed Principle PHP