【设计模式】【策略模式 打折算法】

来源:互联网 发布:普通专升本网络课程 编辑:程序博客网 时间:2024/04/30 12:59
/** * Description: * <br/>网站: <a href="http://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="http://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="http://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 OldDiscountimplements DiscountStrategy{//重写getDiscount()方法,提供旧书打折算法public double getDiscount(double originPrice){System.out.println("使用旧书折扣...");return originPrice * 0.7;}}



/** * Description: * <br/>网站: <a href="http://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="http://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));}}



原创粉丝点击