设计模式--策略模式

接口:

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));
    }
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值