Design Patterns PHP - Strategy Java

1) What have we done?

Firstly we don't crate many versions of "Context". We just inject proper strategies.


class Context
{
    /**
     * @var StrategyA
     */
    protected $strategyA;

    /**
     * @var StrategyB
     */
    protected $strategyB;

    /**
     * @param StrategyA $strategyA
     * @param StrategyB $strategyB
     */
    function __construct(StrategyA $strategyA, StrategyB $strategyB)
    {
        $this->strategyA = $strategyA;
        $this->strategyB = $strategyB;
    }

    public function doA()
    {
        $this->strategyA->doA();
    }

    public function doB()
    {
        $this->strategyB->doB();
    }
}




for method "doA" we inject "StrategyA1" or "StrategyA2"


interface StrategyA
{
    public function doA();
}

class StrategyA1 implements StrategyA
{
    public function doA()
    {
        echo 'DoingA ver1' . PHP_EOL;
    }
}

class StrategyA2 implements StrategyA
{
    public function doA()
    {
        echo 'DoingA ver2' . PHP_EOL;
    }
}




for method "doB" we inject "StrategyB1" or "StrategyB2"


interface StrategyB
{
    public function doB();
}

class StrategyB1 implements StrategyB
{
    public function doB()
    {
        echo 'DoingB ver1' . PHP_EOL;
    }
}

class StrategyB2 implements StrategyB
{
    public function doB()
    {
        echo 'DoingB ver2' . PHP_EOL;
    }
}





2) What have we achieved?

We have two interfaces "StrategyA" and "StrategyB" which we can freely implement and then inject into "Context"

We got rid of code duplication.


$context = new Context(new StrategyA1(), new StrategyB2());
$context->doA();
$context->doB();

$context = new Context(new StrategyA2(), new StrategyB1());
$context->doA();
$context->doB();