Example
interface SortStrategy {
sort(array $data): array;
}
class QuickSort implements SortStrategy { ... }
class MergeSort implements SortStrategy { ... }
class Sorter {
public function __construct(private SortStrategy $strategy) {}
public function sort(array $data): array {
return $this->strategy->sort($data);
}
}
When to use
- There are multiple variants of an algorithm and you need to switch between them
- You want to avoid large if/switch blocks selecting the algorithm
- The behaviour should be configurable from outside or changeable at runtime