[Design Patterns]: Strategy

Another name for this pattern is Policy pattern. In this pattern families of Algorithms are grouped together. This pattern is useful in particularly when several algorithms can perform the same operation and we would like the application to pick up the appropriate algorithm based on specific attributes.

Interfaces serve by providing contracts which must be obeyed by any new concrete implementation.

Example:
In this example there are 2 ways to ship an item: cargo or freight. Based on user’s choice of shipping type the order price will vary.

interface ShippingStrategy
{
    public function getPrice();
}

class ShipByFreight implements ShippingStrategy
{
    public function getPrice()
    {
        return 1000;
    }
}

class ShipByCargo implements ShippingStrategy
{
    public function getPrice()
    {
        return 2000;
    }
}

class Order
{

    private $itemCode;
    private $itemName;
    private $shippingType;

    /**
     * Order constructor.
     */
    public function __construct($itemCode, $itemName, $shippingType)
    {
        $this->itemCode = $itemCode;
        $this->itemName = $itemName;
        $this->shippingType = $shippingType;
    }

    public function getPrice()
    {
        if ($this->shippingType == 'cargo') {
            $shipping = new ShipByCargo();
        } elseif ($this->shippingType == 'freight') {
            $shipping = new ShipByFreight();
        } else {
            throw new Exception('Undefined shipping type: ' . $this->shippingType);
        }

        return $shipping->getPrice();
    }
}


$order = new Order('10029NA', 'iPhone X', 'cargo');

echo $order->getPrice(); 

Majd Arbash

Leave a Reply