大话设计模式二:策略模式(商场促销)

来源:互联网 发布:百雀羚淘宝哪家是真品 编辑:程序博客网 时间:2024/04/29 07:34

    策略模式:它定义了算法家族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化,不会影响到使用的算法客户。 

     应用案例:商场促销的多样性(折扣,满减,积分)

package Strategy;abstract class CashSuper {public abstract double acceptCash(double money);}class CashNormal extends CashSuper {@Overridepublic double acceptCash(double money) {return money;}}class CashRebate extends CashSuper {private double moneyRebate = 1d;public CashRebate(String moneyRebate) {this.moneyRebate = Double.parseDouble(moneyRebate);}@Overridepublic double acceptCash(double money) {return money * moneyRebate;}}class CashReturn extends CashSuper {private double moneyCondition = 0.0d;private double moneyReturn = 0.0d;public CashReturn(String moneyCondition, String moneyReturn) {this.moneyCondition = Double.parseDouble(moneyCondition);this.moneyReturn = Double.parseDouble(moneyReturn);}@Overridepublic double acceptCash(double money) {double result = money;if (money >= moneyCondition) {result = money - Math.floor(money / this.moneyCondition)* this.moneyReturn;}return result;}}public class CashContext {private CashSuper cs;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 static void main(String[] args) {// TODO Auto-generated method stubCashContext cc = null;double total = 0.0d,totalprice = 1000d;cc = new CashContext("正常收费");total = cc.GetResult(totalprice);System.out.println(total);total = 0.0d;totalprice = 1000d;cc = new CashContext("满300返100");total = cc.GetResult(totalprice);System.out.println(total);total = 0.0d;totalprice = 1000d;cc = new CashContext("打8折");total = cc.GetResult(totalprice);System.out.println(total);}}

     策略模式就是用来封装算法的,在实践中,我们发现可以用来封装几乎任何类型的规则,只要在分析中听到需要在不同时间应用不同的业务规则,就可以考虑使用策略模式处理这种变化的可能性。


原创粉丝点击