策略模式(Strategy),是一种定义一系列算法的方法,从概念上来看,所有这些算法完成的都是相同的工作,只是实现不同。它可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间耦合。
策略模式就是用来封装算法的,但在实践中,我们发现可以用它来封装几乎任何类型的规则,只要在分析过程中听到需要在不同时间应用不同的业务规则,就可以考虑使用策略模式处理这种变化的可能性。
CashCollect.java类
package strategy; import java.math.BigDecimal; public abstract class CashCollect { public abstract BigDecimal cashCollect(BigDecimal total); }
DisCountCashCollect.java类
package strategy; import java.math.BigDecimal; public class DisCountCashCollect extends CashCollect { private BigDecimal discount; public DisCountCashCollect(BigDecimal discount) { super(); this.discount = discount; } @Override public BigDecimal cashCollect(BigDecimal total) { System.out.println(total); System.out.println(discount); return total.multiply(discount); } }
NormalCashCollect.java类
package strategy; import java.math.BigDecimal; public class NormalCashCollect extends CashCollect { @Override public BigDecimal cashCollect(BigDecimal total) { return total; } }
RebateCashCollect.java类
package strategy; import java.math.BigDecimal; public class RebateCashCollect extends CashCollect { private BigDecimal fullMoney; private BigDecimal returnMoney; public RebateCashCollect(BigDecimal fullMoney, BigDecimal returnMoney) { super(); this.fullMoney = fullMoney; this.returnMoney = returnMoney; } @Override public BigDecimal cashCollect(BigDecimal total) { if(fullMoney.compareTo(total)>=0){ total = total.subtract(returnMoney); } return total; } }
CashContext.java类
package strategy; import java.math.BigDecimal; public class CashContext { CashCollect cc ; /*public CashContext(CashCollect cc) { super(); this.cc = cc; }*/ public CashContext(String type){ switch(type){ case "原价": cc = new NormalCashCollect(); break; case "打8折": cc = new DisCountCashCollect(new BigDecimal("0.8")); break; case "满300返100": cc = new RebateCashCollect(new BigDecimal("300"), new BigDecimal("100")); break; } } public BigDecimal cashCollect(BigDecimal total ){ return cc.cashCollect(total); } }
BusinessStrategy.java类
package strategy; import java.math.BigDecimal; /** * 策略模式 * @author 煞笔 * */ public class BusinessStrategy { public static void main(String[] args) { //BigDecimal total = new BigDecimal("1000"); CashContext cct = new CashContext("打8折"); //cct.total = total; BigDecimal total = cct.cashCollect(new BigDecimal("1000")); System.out.println(total); } }