In this example, we can learn how to implement Strategy Pattern in Java.
Source Code
1)
package com.beginner.examples;
public interface Strategy1 {
//define operation name
public int operation(int num1, int num2);
}
2)
package com.beginner.examples;
public class Strategy2 implements Strategy1{
@Override
public int operation(int num1, int num2) {
// add
return num1 + num2;
}
}
3)
package com.beginner.examples;
public class Strategy3 implements Strategy1{
@Override
public int operation(int num1, int num2) {
// substract
return num1 - num2;
}
}
4)
package com.beginner.examples;
public class Strategy4 {
private Strategy1 strategy;
public Strategy4(Strategy1 strategy){
this.strategy = strategy;
}
// execute strategy
public int execute(int num1, int num2){
return strategy.operation(num1, num2);
}
}
5)
package com.beginner.examples;
public class StrategyExample {
public static void main(String[] args) {
// execute add operation
Strategy4 s = new Strategy4(new Strategy2());
System.out.println("6 + 1 = " + s.execute(6, 1));
// execute substract operation
s = new Strategy4(new Strategy3());
System.out.println("6 - 1 = " + s.execute(6, 1));
}
}
Output:
6 + 1 = 7
6 - 1 = 5