简介:策略模式是一种定义一系列算法的模式,所有的算法分别是一种处理方法,完成的都是相同的工作,只是方式不一样。使用时,客户端只需选择具体策略实现即可。当有新的策略时,扩展很方便。
代码实现及测试如下:
/**
* 这种常用的代码逻辑违反了开闭原则,即对修改关闭,对扩展开放
* 后期维护需修改大量代码
* @author dedu
*/
public class Popular {
public double calculate(int type, double raw) {
double total = 0;
switch (type) {
case 0:
total = raw * 0.9;
break;
case 1:
total = raw * 0.8;
break;
default:
total = raw;
break;
}
return total;
}
}
/**
* 定义策略抽象接口提供给调用者
* @author dedu
*
*/
public interface Strategy {
public double calculate(double raw);
}
/**
* 一种算法策略
* @author dedu
*/
public class StrategyA implements Strategy {
@Override
public double calculate(double raw) {
return raw * 0.9;
}
}
/**
* 策略B
* @author dedu
*/
public class StrategyB implements Strategy {
@Override
public double calculate(double raw) {
return raw * 0.8;
}
}
/**
* 负责和具体的策略交互,这样策略算法和调用端进行了分隔。
* 具体使用时,分别实现不同策略算法即可。
* @author dedu
*
*/
public class Context {
private Strategy strategy;
public Context(Strategy strategy) {
super();
this.strategy = strategy;
}
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public double calculatePrice(double raw) {
return strategy.calculate(raw);
}
}
测试
public static void main(String[] args) {
Context ctx = new Context(new StrategyA());
double resultA = ctx.calculatePrice(100);
System.out.println(resultA);
ctx.setStrategy(new StrategyB());
double resultB = ctx.calculatePrice(100);
System.out.println(resultB);
}