首页 > 代码库 > 策略模式
策略模式
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); } }
策略模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。