某大型购物中心欲开发一套收银软件,要求其能够支持购物中心在不同时期推出的各种促销活动,如打折、返利(例如,满300返100),等等。现采用策略(Strategy)模式实现该要求,得到如图7.13 所示的类图。
【Java 代码】
import java.util.*;
enum TYPE { NORMAL,CASH_DISCOUNT,CASH_RETURN};
interface Cashsuper {
public double acceptCash(double money);
}
class CashNormal implements CashSuper{// 正常收费子类
public double accptCash(double money){
return money;
}
}
class CashDiscount implements Cashsuper {
private double moneyDiscount; //折扣率
public CashDiscount(double moneyDiscount){
this moneyDiscount = moneyDiscount;
}
public double acceptCash(double money){
return money* moneyDiscount;
}
}
class CashReturn implements Cashsuper { //满额返利
private double moneyCondition;
private double moneyReturn;
public CashReturn(double moneyCondition, double moneyReturn){
this.moneycondition =moneyCondition;//满额数额
this.moneyReturn =moneyReturn;//返利数额
}
public double acceptCash(double money){
double result = money;
if (money >= moneyCondition )
result=money-Math.floor(money/moneyCondition )* moneyReturn;
return result;
}
}
class CashContext_{
private Cashsuper cs;
private TYPE t;
public CashContext(TYPE t){
switch(t){
case NORMAL;// 正常收费
cs= new CashNormal();
break;
case CASH RETURN;//满300返100
cs = new CashReturn(300,100);
break;
case CASH_ DISCOUNT;//打8折
cs =new CashDiscount(0.8);
break;
}
}
public double GetResult(double money){
return cs.acceptCash(money);
}
//此处略去main()函数
}