策略模式(Strategy):
它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化不会影响到使用算法的客户。
public class CashContext {
CasuSuper cs =null;
public CashContext(String type){
switch(type){
case "正常消费":
cs = new CashNormal();
break;
case "满300返100":
cs = new CashReturn(300, 100);
break;
case "打八折":
cs = new CashRebate(0.8);
}
}
public double GetResult(double money){
return cs.acceptCash(money);
}
}
public class CashNormal extends CasuSuper{
public double acceptCash(double money) {
// TODO Auto-generated method stub
return money;
}
public class CashRebate extends CasuSuper {
private double moneyRebate =1.0;
public CashRebate(double moneyRebate) {
this.moneyRebate = moneyRebate;
}
public double acceptCash(double money) {
// TODO Auto-generated method stub
return money*moneyRebate;
}
}
public class CashReturn extends CasuSuper {
private double moneyCondition = 0.0;
private double moneyReturn =0.0;
public CashReturn(double moneyCondition,double moneyReturn)
{
this.moneyCondition =moneyCondition;
this.moneyReturn = moneyReturn;
}
public double acceptCash(double money) {
double result =money;
if(money>=moneyCondition)
{
result = money -Math.floor(money/moneyCondition)*moneyReturn;
}
return result;
}
}
public abstract class CasuSuper {
public abstract double acceptCash(double money);
}
public class StrategyTest {
/**
* @param args
*/
public static void main(String[] args) {
CashContext context = new CashContext("满300返100");
System.out.println(context.GetResult(1000));
}
}
策略模式是一种定义一系列算法的方法。从概念上来看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合。
策略模式的Strategy类层次为Context定义了一系列的可供重用的算法或行为。继承有助于析取出这些算法中的公共功能。
简化单元测试,因为每个算法都有自己的类,可以通过自己的接口单独测试。