手写一个策略模式

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


一、策略模式

痛点:项目中大量的if-else语句,不利于维护,如果业户需求改变,维护起来是非常麻烦,而且一个类中大量的逻辑代码会造成代码冗余。
策略模式属于行为型设计模式的一种,是指一个类的行为或其算法可以在运行时更改。在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象。策略对象改变 context 对象的执行算法。

二、实现一个简单的策略模式

1.需求

我们在网购时,商家为了激发人们的购买欲,会绞尽脑汁设置眼花缭乱的优惠策略,例如各种满减,优惠卷等等。
现有一个订单的Controller,其中有一个方法是checkout(),计算总金额。根据商品种类有如下不同的优惠策略:
1)商品总价满200元减20;
2)商品总价无门槛间15元;
3)商品总价打八五折;
为了简化代码,直接给定商品总原价totalPrice。
如果不使用设计模式:相信大家都会写

public double checkout(double totalPrice, int discountType) {
	if(discountType == 1){
		if(totalPrice >= 200) totalPrice -= 20;
		else return totalPrice ;
	}else if(discountType == 2){
		totalPrice -= 10;
	}else if(discountType == 3){
		totalPrice *= 0.85;
	}
	return totalPrice;
}

2.使用策略模式

实现步骤:

  1. 首先创建一个DiscountsStrategy接口
public interface DiscountsStrategy {
    public double getTotalPrice(double totalPrice);
}
  1. 然后根据策略类,创建DiscountsStrategy的一些实现类:
public class Strategy1 implements DiscountsStrategy {

    @Override
    public double getTotalPrice(double totalPrice) {
        return totalPrice >= 200 ? totalPrice - 20 : totalPrice;
    }
}

public class Strategy2 implements DiscountsStrategy {

    @Override
    public double getTotalPrice(double totalPrice) {
        return totalPrice - 15;
    }
}

public class Strategy3 implements DiscountsStrategy {

    @Override
    public double getTotalPrice(double totalPrice) {
        return totalPrice * 0.85;
    }
}
  1. 创建策略对象Context
public class Context {
    private DiscountsStrategy discountsStrategy;
    public Context(DiscountsStrategy discountsStrategy){
        this.discountsStrategy = discountsStrategy;
    }

    public double getTotalPrice(double totalPrice){
        return discountsStrategy.getTotalPrice(totalPrice);
    }
}
  1. 修改checkout代码
public double checkout(double totalPrice, int discountType) {
	
	Context context;
	if(discountType = 1) context = new Context(new Strategy1());
	else if(discountType == 2) context = new Context(new Strategy2());
	else if(discountType == 3) context = new Context(new Strategy3());
	return context.getTotalPrice(totalPrice);
	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值