569
技術社區[雲棲]
【設計模式】【策略模式 打折算法】
/** * Description: * <br/>網站: <a href="https://www.crazyit.org">瘋狂Java聯盟</a> * <br/>Copyright (C), 2001-2012, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public interface DiscountStrategy { //定義一個用於計算打折價的方法 double getDiscount(double originPrice); }
/** * Description: * <br/>網站: <a href="https://www.crazyit.org">瘋狂Java聯盟</a> * <br/>Copyright (C), 2001-2012, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ //實現DiscountStrategy接口,實現對VIP打折的算法 public class VipDiscount implements DiscountStrategy { //重寫getDiscount()方法,提供VIP打折算法 public double getDiscount(double originPrice) { System.out.println("使用VIP折扣..."); return originPrice * 0.5; } }
/** * Description: * <br/>網站: <a href="https://www.crazyit.org">瘋狂Java聯盟</a> * <br/>Copyright (C), 2001-2012, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class OldDiscount implements DiscountStrategy { //重寫getDiscount()方法,提供舊書打折算法 public double getDiscount(double originPrice) { System.out.println("使用舊書折扣..."); return originPrice * 0.7; } }
/** * Description: * <br/>網站: <a href="https://www.crazyit.org">瘋狂Java聯盟</a> * <br/>Copyright (C), 2001-2012, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class DiscountContext { //組合一個DiscountStrategy對象 private DiscountStrategy strategy; //構造器,傳入一個DiscountStrategy對象 public DiscountContext(DiscountStrategy strategy) { this.strategy = strategy; } //根據實際所使用的DiscountStrategy對象得到折扣價 public double getDiscountPrice(double price) { //如果strategy為null,係統自動選擇OldDiscount類 if (strategy == null) { strategy = new OldDiscount(); } return this.strategy.getDiscount(price); } //提供切換算法的方法 public void changeDiscount(DiscountStrategy strategy) { this.strategy = strategy; } }
/** * Description: * <br/>網站: <a href="https://www.crazyit.org">瘋狂Java聯盟</a> * <br/>Copyright (C), 2001-2012, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class StrategyTest { public static void main(String[] args) { //客戶端沒有選擇打折策略類 DiscountContext dc = new DiscountContext(null); double price1 = 79; //使用默認的打折策略 System.out.println("79元的書默認打折後的價格是:" + dc.getDiscountPrice(price1)); //客戶端選擇合適的VIP打折策略 dc.changeDiscount(new VipDiscount()); double price2 = 89; //使用VIP打折得到打折價格 System.out.println("89元的書對VIP用戶的價格是:" + dc.getDiscountPrice(price2)); } }
最後更新:2017-04-04 07:03:38