Sobes.tech
Middle

How do you implement the 'Strategy' design pattern in PHP?

sobes.tech AI

Answer from AI

The Strategy pattern allows encapsulating different algorithms into separate classes and making them interchangeable at runtime. The client code works with a common interface for strategies without knowing their specific implementations.

Implementation in PHP includes:

  1. Strategy Interface: Defines a common method that all concrete strategies will implement.
  2. Concrete Strategies: Classes that implement the interface and contain specific algorithm logic.
  3. Context: A class that holds a reference to a strategy object and delegates method execution to this object.

Example:

<?php
// 1. Strategy Interface
interface SortStrategy
{
    public function sort(array $data): array;
}

// 2. Concrete Strategy (Bubble Sort)
class BubbleSortStrategy implements SortStrategy
{
    public function sort(array $data): array
    {
        $n = count($data);
        for ($i = 0; $i < $n; $i++) {
            for ($j = 0; $j < $n - 1 - $i; $j++) {
                if ($data[$j] > $data[$j + 1]) {
                    $temp = $data[$j];
                    $data[$j] = $data[$j + 1];
                    $data[$j + 1] = $temp;
                }
            }
        }
        return $data;
    }
}

// 2. Concrete Strategy (Quick Sort)
class QuickSortStrategy implements SortStrategy
{
    public function sort(array $data): array
    {
        // Simple implementation for example, recursion in real code
        sort($data); // Using built-in function for illustration
        return $data;
    }
}

// 3. Context
class SortedList
{
    private SortStrategy $strategy;
    private array $data;

    public function __construct(array $data)
    {
        $this->data = $data;
    }

    public function setSortStrategy(SortStrategy $strategy): void
    {
        $this->strategy = $strategy;
    }

    public function sort(): array
    {
        if (!isset($this->strategy)) {
            throw new \RuntimeException("Sorting strategy not set.");
        }
        return $this->strategy->sort($this->data);
    }
}

// Usage
$data = [5, 2, 8, 1, 9, 4];
$sortedList = new SortedList($data);

// Using bubble sort
$sortedList->setSortStrategy(new BubbleSortStrategy());
$sortedDataBubble = $sortedList->sort();
print_r($sortedDataBubble);

// Using quick sort
$sortedList->setSortStrategy(new QuickSortStrategy());
$sortedDataQuick = $sortedList->sort();
print_r($sortedDataQuick);

Advantages:

  • Flexibility: Easily add new sorting algorithms without changing the context.
  • Extensibility: New strategies can be implemented independently.
  • Code cleanliness: The context is separated from the logic of specific algorithms.
  • Testability: Each strategy can be tested in isolation.
How do you implement the 'Strategy' design pattern in… - sobes.tech