DEV Community

eidher
eidher

Posted on • Edited on

Strategy Pattern

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
Alt Text

Participants

  • Strategy: declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy
  • ConcreteStrategy: implements the algorithm using the Strategy interface
  • Context: is configured with a ConcreteStrategy object. Maintains a reference to a Strategy object. May define an interface that lets Strategy access its data.

Code

public class Main {

    public static void main(String[] args) {
        Context context;
        context = new Context(new ConcreteStrategyA());
        context.contextInterface();
        context = new Context(new ConcreteStrategyB());
        context.contextInterface();
    }
}

public interface Strategy {

    void algorithmInterface();

}

public class ConcreteStrategyA implements Strategy {

    @Override
    public void algorithmInterface() {
        System.out.println("Called ConcreteStrategyA.AlgorithmInterface()");
    }

}

public class ConcreteStrategyB implements Strategy {

    @Override
    public void algorithmInterface() {
        System.out.println("Called ConcreteStrategyB.AlgorithmInterface()");
    }

}

public class Context {
    private Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public void contextInterface()  {
        strategy.algorithmInterface();
    }
}

Enter fullscreen mode Exit fullscreen mode

Output

Called ConcreteStrategyA.AlgorithmInterface()
Called ConcreteStrategyB.AlgorithmInterface()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)