提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
一、策略模式
痛点:项目中大量的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.使用策略模式
实现步骤:
- 首先创建一个DiscountsStrategy接口
public interface DiscountsStrategy {
public double getTotalPrice(double totalPrice);
}
- 然后根据策略类,创建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;
}
}
- 创建策略对象Context
public class Context {
private DiscountsStrategy discountsStrategy;
public Context(DiscountsStrategy discountsStrategy){
this.discountsStrategy = discountsStrategy;
}
public double getTotalPrice(double totalPrice){
return discountsStrategy.getTotalPrice(totalPrice);
}
}
- 修改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);
}