Design Patterns PHP - Bridge Java

1) What have we done?

First of all we created interface "Implementator" which defines methods which previously was defined as non-public in "ClassA"


interface Implementator
{
    public function doStep1();

    public function doStep2();

    public function doStep3();
}

class ImplementatorOne implements Implementator
{
    public function doStep1()
    {
        echo 'ImplementatorOne doing step 1' . PHP_EOL;
    }

    public function doStep2()
    {
        echo 'ImplementatorOne doing step 2' . PHP_EOL;
    }

    public function doStep3()
    {
        echo 'ImplementatorOne doing step 3' . PHP_EOL;
    }
}

class ImplementatorTwo implements Implementator
{
    public function doStep1()
    {
        echo 'ImplementatorTwo doing step 1' . PHP_EOL;
    }

    public function doStep2()
    {
        echo 'ImplementatorTwo doing step 2' . PHP_EOL;
    }

    public function doStep3()
    {
        echo 'ImplementatorTwo doing step 3' . PHP_EOL;
    }
}




And into "ClassA" we inject in constructor proper implementation "doA" we implement by proper "Implementator" object.

In subclass "ClassAB" method "doB" we also implements thanks to "Implementator" object


class ClassA
{
    /**
     * @var Implementator
     */
    protected $implementator;

    /**
     * @param Implementator $implementator
     */
    function __construct(Implementator $implementator)
    {
        $this->implementator = $implementator;
    }

    public function doA()
    {
        $this->implementator->doStep1();
        $this->implementator->doStep2();
        $this->implementator->doStep3();
    }
}

class ClassAB extends ClassA
{
    public function doB()
    {
        $this->implementator->doStep2();
        $this->implementator->doStep3();
        $this->implementator->doStep1();
    }
}




2) What are the benefits ?

Let see on file "Client.php"


$implementatorOne = new ImplementatorOne();
$implementatorTwo = new ImplementatorTwo();

$classA = new ClassA($implementatorOne);
$classA->doA();

$classAB = new ClassAB($implementatorTwo);
$classAB->doB();




For "ClassA" or "ClassAB" we can inject any implementator.

There is no code duplication. We have full flexibility of injecting any implementator to any class.