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
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?