Glossary

Strategy Pattern

Strategy is a pattern that extracts a varying behaviour into a separate class (the strategy) and allows it to be swapped at runtime. The class depends on the strategy interface, not on a concrete implementation.

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