Design Patterns Java - Strategy Php

1) What have we done?

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


public class Context
{
    StrategyA strategyA;

    StrategyB strategyB;

    public Context(StrategyA strategyA, StrategyB strategyB)
    {
        this.strategyA = strategyA;
        this.strategyB = strategyB;
    }

    public void doA()
    {
        strategyA.doA();
    }

    public void doB()
    {
        strategyB.doB();
    }
}




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


public interface StrategyA
{
    void doA();
}

public class StrategyA1 implements StrategyA
{
    @Override
    public void doA()
    {
        System.out.println("DoingA version1");
    }
}

public class StrategyA2 implements StrategyA
{
    @Override
    public void doA()
    {
        System.out.println("DoingA version2");
    }
}




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


public interface StrategyB
{
    void doB();
}

public class StrategyB1 implements StrategyB
{
    @Override
    public void doB()
    {
        System.out.println("DoingB version1");
    }
}

public class StrategyB2 implements StrategyB
{
    @Override
    public void doB()
    {
        System.out.println("DoingB version2");
    }
}





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.


public class Client
{
    public static void main(String[] args)
    {
        Context context = new Context(new StrategyA1(), new StrategyB2());
        context.doA();
        context.doB();

        context = new Context(new StrategyA2(), new StrategyB1());
        context.doA();
        context.doB();
    }
}