实例
我们将创建一个定义操作的“Strategy”接口和实现该“Strategy”接口的具体策略类。Context 是使用策略的类。
我们的演示类StrategyPatternDemo将使用Context和strategy对象根据其部署或使用的策略来演示Context行为的变化。
第1步 - 创建一个接口。 Strategy.java
public interface Strategy {
public int doOperation(int num1, int num2);
}
第2步 - 创建实现相同接口的具体类。 OperationAdd.java , OperationSubstract.java, OperationMultiply.java
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;
}
}
第3步 - 创建上下文类。 Context.java
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);
}
}
步骤4 - 使用上下文可以查看其更改策略时的行为变化。 StrategyPatternDemo.java
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));
}
}
第5步 - 验证输出。
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50