Strategy Pattern

Strategy is a behavioral design pattern which is used for changing class behavior or its algorithm at run time. With Strategy pattern, developer creates objects which represent various strategies and a context object whose behavior varies as per its strategy object. The strategy object changes the executing algorithm of the context object.

The following example contains Strategy interface defining an action and concrete strategy classes implementing the Strategy interface. Context is a class which uses a Strategy. Demo class StrategyPatternDemo will use Context and strategy objects to demonstrate change in Context behavior based on strategy it deploys or uses.

Strategy Pattern UML Diagram

Step 1 : Create an interface

public interface Strategy {
int doOperation(int num1, int num2);
}

Step 2 : Create concrete classes implementing the same interface

public class OperationAdd implements Strategy {
@Override
public int doOperation(int num1, int num2) {
return num1 + num2;
}
}

public class OperationSubstract implements Strategy {
@Override
public int doOperation(int num1, int num2) {
return num1 - num2;
}
}

public class OperationMultiply implements Strategy {
@Override
public int doOperation(int num1, int num2) {
return num1 * num2;
}
}

Step 3 : Create Context class

public class Context {
private Strategy strategy;

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

public int executeStrategy(int num1, int num2) {
return strategy.doOperation(num1, num2);
}
}

Step 4 : Use the Context class to see change in behavior when it changes its Strategy

public class StrategyPatternDemo {
public static void main(String[] args) {
Context context = new Context(new OperationAdd());
System.out.println("10 + 5 = " + context.executeStrategy(10, 5));

context = new Context(new OperationSubstract());
System.out.println("10 - 5 = " + context.executeStrategy(10, 5));

context = new Context(new OperationMultiply());
System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
}
}

The output will be :

10 + 5 = 15
10 - 5 = 5
10 * 5 = 50

Leave a Reply

Your email address will not be published. Required fields are marked *