设计模式--策略模式

来源:互联网 发布:学日语 知乎 编辑:程序博客网 时间:2024/06/07 06:23

接口:

public interface Discount {    public double getDiscountPrice(double orignalPrice);}

实现类:

public class OldDiscount implements Discount {    @Override    public double getDiscountPrice(double originPrice) {        // TODO Auto-generated method stub        return 0.5*originPrice;    }}
public class VipDiscount implements Discount {    @Override    public double getDiscountPrice(double orignalPrice) {        // TODO Auto-generated method stub        return 0.4*orignalPrice;    }}
package com.design.strategymodel;/** * 整体为策略模式与简单工厂模式的结合版 * @author Tang * */public class DiscountContext {    private Discount strategy;    /**     * 该处采用简单工厂模式指定的打折对象     * @param strategyStr     */    public DiscountContext(String strategyStr) {        switch (strategyStr) {        case "默认打折":            strategy = new OldDiscount();            break;        case "打VIP打折":            strategy = new VipDiscount();            break;        }    }    /*public DiscountContext(Discount discount){        this.strategy=discount;    }*/    public double getDiscountPrice(double price) {        if (strategy == null) {            strategy = new OldDiscount();        }        return this.strategy.getDiscountPrice(price);    }}

测试:

public class TextMain {    public static void main(String[] args) {        // 客户端没有选择打折策略类        DiscountContext dcOld = new DiscountContext("默认打折");        double price1 = 79;        // 使用默认的打折策略        System.out.println("79元的书默认打折后的价格是:" + dcOld.getDiscountPrice(price1));        // 客户端选择合适的VIP打折策略        DiscountContext dcVip = new DiscountContext("打VIP打折");        double price2 = 89;        // 使用VIP打折得到打折价格        System.out.println("89元的书对VIP用户的价格是:" + dcVip.getDiscountPrice(price2));    }}

策略模式与简单工厂模式类似,但是比简单工厂模式封装得更加深一下,不再是通过工厂返回对象,而是为接口引用指向不同的实现对象来实现不同策略。在控制类中,可以通过工厂方法模式的思想,通过工厂来为接口引用指向不同的实现类对象。具体思想可查看上述代码。
参考《大话设计模式》。

原创粉丝点击