策略模式的基本运用

来源:互联网 发布:淘宝店铺首页怎么上传 编辑:程序博客网 时间:2024/05/16 20:27

购买商品后有三种优惠,根据不同情况选择不同的优惠措施。使用策略模式可以实现较好的封装,但仍有需要改进的地方。

/** * 现金收费抽象类 */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=1d;    public CashRebate(double moneyRebate){        this.moneyRebate=moneyRebate;    }    @Override    public double acceptCash(double money) {        return money*moneyRebate;    }}/** * 返利收费子类 */class CashReturn extends CashSuper{    private double moneyCondition=0.0d;//返利条件    private double moneyReturn=0.0d;    public CashReturn(double moneyCondition,double moneyReturn){        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 "正常收费":                CashNormal cs0=new CashNormal();                cs=cs0;                break;            case "满300返100":                CashReturn cr1=new CashReturn(300,100);                cs=cr1;                break;            case "打八折":                CashRebate cr2=new CashRebate(0.8);                cs=cr2;                break;        }    }    public double GetResult(double money){        return cs.acceptCash(money);    }}
/** * 客户端调用 */public class Strategy {    public static void main(String[] args){        CashContext csuper=new CashContext("正常收费");        double prices=csuper.GetResult(1000);        CashContext csuper2=new CashContext("满减");        double prices2=csuper2.GetResult(1000);    }}
原创粉丝点击