abstract class CashSuper {
public abstract double acceptCash(double money);}
//正常收費子類
class CashNormal extends CashSuper {
@Override
public double acceptCash(double money) {
return money;
}}
//打折收費子類
class CashRebate extends CashSuper {
private double moneyRebate = 1.0;
public CashRebate(double moneyRebate) {
super();this.moneyRebate = moneyRebate;
}
@Override
public double acceptCash(double money) {
return money*moneyRebate;
}}
//返利收費子類
class CashReturn extends CashSuper {
private double moneyCondition = 0.0;
private double moneyReturn = 0.0;
public CashReturn(double moneyCondition, double moneyReturn) {
super();this.moneyCondition = moneyCondition;this.moneyReturn = moneyReturn;
}
@Override
public double acceptCash(double money) {
double result = money;if(money >= moneyCondition) {
result = money - Math.floor(money/moneyCondition)*moneyReturn;
}return result;
}
}
//策略模式類(結合工廠模式)
class CashContext {
CashSuper cs = null;
public CashContext(String type) {
switch(type) {
case "正常收費":
cs = new CashNormal();break;
case "滿300反100":
cs = new CashReturn(300,100);break;
case "打8折":
cs = new CashRebate(0.8);break;
}}
public double getResult(double money) {
return cs.acceptCash(money);
}
}
//客戶端代碼
public class Main
{
public static void main(String[] args) throws Exception {
CashContext cc1 = new CashContext("滿300反100");}
System.out.println(cc1.getResult(1000));
CashContext cc2 = new CashContext("打8折");
System.out.println(cc2.getResult(1000));
}