DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Strategy

In a Strategy pattern, a class behavior or algorithm can be changed at run time. This type of design pattern comes under behavior pattern.
In the Strategy pattern, we create objects representing various strategies and a context object whose behavior varies per its strategy object. The strategy object changes the executing algorithm of the context object.
The strategy pattern is nothing but OCP (Open-close Principle) i.e. one of the solid principles which states that the object should be open for extension but closed for modification.

Read more about OCP

Consider an example of Mathematical Operations as strategies.
We will try to use these strategies in different contexts.

strategy
Strategy

public interface Strategy {
    public int doOperation(int a, int b);
}
Enter fullscreen mode Exit fullscreen mode

Concrete Strategies

public class AdditionStrategy implements Strategy {
    @Override
    public int doOperation(int a, int b){
        System.out.println("performing + operation");
        return a+b;
    }
}

public class MultiplyStrategy implements Strategy {
    @Override
    public int doOperation(int a, int b){
        System.out.println("performing x operation");
        return a*b;
    }
}


public class SubtractStrategy implements Strategy {
    @Override
    public int doOperation(int a, int b){
        System.out.println("performing - operation");
        return a-b;
    }
}
Enter fullscreen mode Exit fullscreen mode

Context: which will used to initialize the strategy

public class Context {
    private Strategy strategy;
    public Context(Strategy s){
        this.strategy = s;
    }
    public void executeStrategy(int a, int b){
        System.out.println(this.strategy.doOperation(a, b));
    }
}
Enter fullscreen mode Exit fullscreen mode

Main

public class Main {
    public static void main(String args[]){
        Context context = new Context(new AdditionStrategy());
        int a = 9, b = 6;
        System.out.println("Add=>"+a+","+b+": "+ context.executeStrategy(a, b));
        Context context2 = new Context(new SubtractStrategy());
        System.out.println("Subtract=>"+a+","+b+": "+ context2.executeStrategy(a, b));
        Context context3 = new Context(new MultiplyStrategy());
        System.out.println("Multiply=>"+a+","+b+": "+ context3.executeStrategy(a, b));
    }
}
Enter fullscreen mode Exit fullscreen mode
Add=>9,6: 15
Subtract=>9,6: 3
Multiply=>9,6: 54
Enter fullscreen mode Exit fullscreen mode

Key takeaways

  • The Strategy pattern allows us to add more strategies in the future like divide, modulo, or such Mathematical family of operations.
  • This strictly follows the OCP(Open-Close principle)
  • The reference variable Strategy is updated at run time, thus updating the behavior of the Strategy algorithm ( add, sub, multiply, etc)

Top comments (0)