Design Patterns Java - Bridge Php

1) What have we done?

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


public interface Implementator
{
    void doStep1();

    void doStep2();

    void doStep3();
}





public class ImplementatorOne implements Implementator
{
    public void doStep1()
    {
        System.out.println("ImplementatorOne doing step1");
    }

    public void doStep2()
    {
        System.out.println("ImplementatorOne doing step2");
    }

    public void doStep3()
    {
        System.out.println("ImplementatorOne doing step3");
    }
}

public class ImplementatorTwo implements Implementator
{
    public void doStep1()
    {
        System.out.println("ImplementatorTwo doing step1");
    }

    public void doStep2()
    {
        System.out.println("ImplementatorTwo doing step2");
    }

    public void doStep3()
    {
        System.out.println("ImplementatorTwo doing step3");
    }
}




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


public class ClassA
{
    protected Implementator implementator;

    public ClassA(Implementator implementator)
    {
        this.implementator = implementator;
    }

    public void doA()
    {
        implementator.doStep1();
        implementator.doStep2();
        implementator.doStep3();
    }
}

public class ClassAB extends ClassA
{
    public ClassAB(Implementator implementator)
    {
        super(implementator);
    }

    public void doB()
    {
        implementator.doStep2();
        implementator.doStep3();
        implementator.doStep1();
    }
}




2) What are the benefits?

Let see on file "Client.java"


public class Client
{
    public static void main(String[] args)
    {
        Implementator implementatorOne = new ImplementatorOne();
        Implementator implementatorTwo = new ImplementatorTwo();

        ClassA classA = new ClassAB(implementatorOne);
        classA.doA();

        ClassAB 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.