Java策略模式
// 定义策略接口
public interface Strategy {
public int doOperation(int num1, int num2);
}
// 实现具体策略:加法
public class OperationAdd implements Strategy {
@Override
public int doOperation(int num1, int num2) {
return num1 + num2;
}
}
// 实现具体策略:减法
public class OperationSubtract 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;
}
}
//上下文类,将使用策略
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);
}
}
// 测试策略模式
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 OperationSubtract()); // 创建上下文并设置减法策略
System.out.println("10 - 5 = " + context.executeStrategy(10, 5)); // 执行减法策略
context = new Context(new OperationMultiply()); // 创建上下文并设置乘法策略
System.out.println("10 * 5 = " + context.executeStrategy(10, 5)); // 执行乘法策略
}
}