DESIGN PATTERNS - STRATEGY PATTERN
[Link] Copyright © [Link]
In Strategy pattern, a class behavior or its algorithm can be changed at run time. This type of
design pattern comes under behavior pattern.
In Strategy pattern, we create 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.
Implementation
We are going to create a Strategy interface defining an action and concrete strategy classes
implementing the Strategy interface. Context is a class which uses a Strategy.
StrategyPatternDemo, our demo class, will use Context and strategy objects to demonstrate
change in Context behaviour based on strategy it deploys or uses.
Step 1
Create an interface.
[Link]
public interface Strategy {
public int doOperation(int num1, int num2);
}
Step 2
Create concrete classes implementing the same interface.
[Link]
public class OperationAdd implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 + num2;
}
}
[Link]
public class OperationSubstract implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 - num2;
}
}
[Link]
public class OperationMultiply implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 * num2;
}
}
Step 3
Create Context Class.
[Link]
public class Context {
private Strategy strategy;
public Context(Strategy strategy){
[Link] = strategy;
}
public int executeStrategy(int num1, int num2){
return [Link](num1, num2);
}
}
Step 4
Use the Context to see change in behaviour when it changes its Strategy.
[Link]
public class StrategyPatternDemo {
public static void main(String[] args) {
Context context = new Context(new OperationAdd());
[Link]("10 + 5 = " + [Link](10, 5));
context = new Context(new OperationSubstract());
[Link]("10 - 5 = " + [Link](10, 5));
context = new Context(new OperationMultiply());
[Link]("10 * 5 = " + [Link](10, 5));
}
}
Step 5
Verify the output.
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50