策略模式(strategy):它定义了算法家族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户。
主方法
/**
* Created by king on 2017/7/6.
*/
public class main {
public static void main(String[] args) {
double total = 1000.0;
int type = 2;
CashContext cc = null;
switch (type) {
case 1 : //正常收费
cc = new CashContext(new CashNormal());
break;
case 2 : //满300返100
cc = new CashContext(new CashReturn(300,100));
break;
case 3: //打8折
cc = new CashContext(new CashRebate(0.8));
break;
}
System.out.println(cc.getResult(total));
}
}
父类
public class CashContext {
private CashSuper cs;
public CashContext (CashSuper cashSuper) {
this.cs = cashSuper;
}
public double getResult(double money) {
return cs.acceptCash(money);
}
}
子类
public abstract class CashSuper {
public abstract double acceptCash(double money);
}
孙子类
正常收费
public class CashNormal extends CashSuper {
@Override
public double acceptCash(double money) {
return money;
}
}
满减
public class CashReturn extends CashSuper {
private double moneyCondition = 0.0d;
private double moenyReturn = 0.0d;
public CashReturn(double moneyCondition, double moenyReturn) {
this.moneyCondition = moneyCondition;
this.moenyReturn = moenyReturn;
}
public double acceptCash(double money) {
double result = money;
if (money >= moneyCondition)
result = money - Math.floor(money / moneyCondition) * moenyReturn;
return result;
}
}
折扣
public class CashRebate extends CashSuper {
private double moneyRebate = 1d;
public CashRebate(double moneyRebate) {
this.moneyRebate = moneyRebate;
}
@Override
public double acceptCash(double money) {
return money * moneyRebate;
}
}