以商场打折为例
package Strategy;
public abstract class CashSuper {
protected abstract Double acceptCash(Double money);
}
package Strategy;
/**
* 正常收费
* @author Modun
*
*/
public class CashNormal extends CashSuper{
@Override
protected Double acceptCash(Double money) {
return money;
}
}
package Strategy;
/**
* 打折收费
* @author Modun
*
*/
public class CashRebate extends CashSuper{
private double rebate;
public CashRebate(Double rebate){
this.rebate = rebate;
}
@Override
protected Double acceptCash(Double money) {
return money * rebate;
}
}
package Strategy;
/**
* 满多少返多少收费
* @author Modun
*
*/
public class CashReturn extends CashSuper{
private Double moneyCondition;
private Double moneyReturn;
public CashReturn(Double moneyCondition, Double moneyReturn){
this.moneyCondition = moneyCondition;
this.moneyReturn = moneyReturn;
}
@Override
protected Double acceptCash(Double money) {
if (money >= moneyCondition) {
return money - (moneyReturn * Math.floor((money / moneyCondition)));
}
return money;
}
}
package Strategy;
public class CashContext {
private CashSuper cs;
public CashContext(String type){
if (type.equals("正常")) {
cs = new CashNormal();
}else if(type.equals("8折")){
cs = new CashRebate(0.8);
}else if(type.equals("满300减100")){
cs = new CashReturn(300.0, 100.0);
}else{
throw new IllegalArgumentException("不支持的促销方式");
}
}
public Double getResult(Double money){
return cs.acceptCash(money);
}
}
package Strategy;
public class Program {
public static void main(String[] args) {
CashContext c1 = new CashContext("正常");
CashContext c2 = new CashContext("8折");
CashContext c3 = new CashContext("满300减100");
System.out.println("总价格为400元,您应付款:" + c1.getResult(400.0));
System.out.println("总价格为400元,您应付款:" + c2.getResult(400.0));
System.out.println("总价格为400元,您应付款:" + c3.getResult(400.0));
System.out.println("总价格为600元,您应付款:" + c3.getResult(600.0));
}
}