类结构:
//父类,商场结账的算法
public interface SuperCash {
//得到算过后的结账金额
public double getcash(double cash);
}
//正常的结账
public class NormalCash implements SuperCash{
public double getcash(double cash) {
return cash;
}
}
//对购买的货物进行打折的结账方式
public class DiscountCash implements SuperCash{
private float moneyRebate;//打折的折扣
public DiscountCash(float moneyRebate){
this.moneyRebate=moneyRebate;
}
public double getcash(double cash) {
return moneyRebate*cash;
}
}
//买五百送三百的这种方式结账
public class ReturnCash implements SuperCash{
private float upcash;//五百
private float downcash;//三百
public ReturnCash(float upcash,float downcash){
this.upcash=upcash;
this.downcash=downcash;
}
public double getcash(double cash) {
double result=cash;
if(cash>=upcash){
result=cash-(Math.floor(cash/upcash)*downcash);
}
return result;
}
}
//算法选择,并输出结果
public class CashContext {
private SuperCash supercash;
public CashContext(String type){
//超市收款用多个算法类来进行使用和选择
if("正常收费".equals(type)){
supercash=new NormalCash();
}else if(type.matches("打.+折")){
float cash=Float.parseFloat(type.replaceAll("打(.+)折", "$1"));
supercash=new DiscountCash(cash/10);
}else if(type.matches("满.+送.+")){
float cashup=Float.parseFloat(type.replaceAll("满(.+)送.+", "$1"));
float cashdown=Float.parseFloat(type.replaceAll("满.+送(.+)", "$1"));
supercash=new ReturnCash(cashup,cashdown);
}
}
public double getResult(double cash){
return supercash.getcash(cash);
}
}
public class Test {
//策略模式:策略封装了变化
//也就是超市收款用多个算法类来进行使用和选择
public static void main(String[] args) {
// String type="正常收费";//输出:400.0
// String type="打8折";//输出:320.0000047683716
String type="满150送50";//输出:300.0
CashContext context = new CashContext(type);
double cash=context.getResult(400);
System.out.println(cash);
}
}