public abstract class CashSuper {
public abstract double acceptCash(double money);
}
3. 封装具体的算法
1. 正常收费具体类
public class CashNormal extends CashSuper{
@Override
public double acceptCash(double money) {
return money;
}
}
2.打折收费类
public class CashRebate extends CashSuper{
private double discount;
public CashRebate(String discount){
this.discount = Double.valueOf(discount);
}
@Override
public double acceptCash(double money) {
return money * discount;
}
}
3.满多少返多少收费类
public class CashReturn extends CashSuper{
//返利条件
private double moneyCondition;
//返价多少
private double moneyReturn;
public CashReturn(String moneyCondition,String moneyReturn){
this.moneyCondition = Double.valueOf(moneyCondition);
this.moneyReturn = Double.valueOf(moneyReturn);
}
@Override
public double acceptCash(double money) {
double result = money;
if(money >= moneyCondition){
result = money - Math.floor(money / moneyCondition) * moneyReturn;
}
return result;
}
}
4. 创建一个Context类,维护一个公共接口或者抽象类的引用
public class CashContext {
private CashSuper cashSuper;
public CashContext(CashSuper cashSuper){
this.cashSuper = cashSuper;
}
/**
* 返回的最终价格
* @param money
* @return
*/
public double getResult(double money){
return cashSuper.acceptCash(money);
}
}
5. 策略模式与简单工厂模式相结合
public class CashContextImprove {
private CashSuper cash;
public CashContextImprove(String type){
switch (type){
case "正常收费":
cash = new CashNormal();
break;
case "打8折":
cash = new CashRebate("0.8");
break;
case "满500返100":
cash = new CashReturn("500","100");
break;
case "满800返200":
cash = new CashReturn("800","200");
break;
}
}
/**
* 返回的最终价格
* @param money
* @return
*/
public double getResult(double money){
return cash.acceptCash(money);
}
}
6. 测试类
1.策略模式
@org.junit.Test
public void test1(){
double totalPrice;
CashContext cc;
cc = selectDiscount("正常收费");
totalPrice = cc.getResult(500);
System.out.println("正常收费价格:"+totalPrice);
cc = selectDiscount("打8折");
totalPrice = cc.getResult(500);
System.out.println("打8折价格:"+totalPrice);
cc = selectDiscount("满500返100");
totalPrice = cc.getResult(500);
System.out.println("满500减100价格:"+totalPrice);
}
public CashContext selectDiscount(String discount){
CashContext cashContext = null;
switch (discount){
case "正常收费":
cashContext = new CashContext(new CashNormal());
break;
case "打8折":
cashContext = new CashContext(new CashRebate("0.8"));
break;
case "满500返100":
cashContext = new CashContext(new CashReturn("500","100"));
break;
}
return cashContext;
}
2. 策略模式与简单工厂模式相结合
@org.junit.Test
public void test2(){
CashContextImprove cci;
double totalPrice;
cci = new CashContextImprove("正常收费");
totalPrice = cci.getResult(500);
System.out.println("正常收费价格:"+totalPrice);
cci = new CashContextImprove("打8折");
totalPrice = cci.getResult(500);
System.out.println("打8折价格:"+totalPrice);
cci = new CashContextImprove("满800返200");
totalPrice = cci.getResult(900);
System.out.println("满500返100价格:"+totalPrice);
}