【设计模式】行为型设计模式之 策略模式学习实践

news/2024/10/17 22:28:58/

介绍

策略模式(Strategy),就是⼀个问题有多种解决⽅案,选择其中的⼀种使⽤,这种情况下我们
使⽤策略模式来实现灵活地选择,也能够⽅便地增加新的解决⽅案。⽐如做数学题,⼀个问题的
解法可能有多种;再⽐如商场的打折促销活动,打折⽅案也有很多种,有些商品是不参与折扣活
动要按照原价销售,有些商品打8.5折,有些打6折,有些是返现5元等。

优缺点和场景

优点

  1. 完美符合开闭原则,可以再不修改原系统基础上选择算法行为,或者新增新的算法。
  2. 策略模式,将一类算法进行了抽象,可以将公共部分进行抽离。避免重复代码。
  3. 策略模式对算法的封装,将算法的责任和算法本身分割开,交给不同的对象管理。提供了可替换继承关系的办法,如果不用策略模式,那么环境类,可能自己就有多个子类了,算法和算法的使用还在一起,那就不符合开闭原则。
  4. 可以避免多重条件选择语句。
  5. 算法抽离后,更方便不同的环境类复用。

缺点

  1. 客户端必须知道所有的策略类,并且决定使用哪一个。
  2. 造成了很多具体的策略的类,细小的变化都需要增加新的具体策略类。

使用场景

  1. 系统需要动态的在某些算法里进行选择,那么使用策略模式,用户只要维持一个算法的抽象类对象即可。
  2. 一个对象有很多的行为,避免在一个类里,根据不同的条件进行多重条件判断时。(if(a) 行为a if(b)行为b 将a和b拆成两个具体类。) 可以使用策略模式,将不同的行为,抽象成具体的策略类。
  3. 需要将具体的算法实现,和使用者进行解耦,提高算法的保密性和安全性。

结构

略模式对算法的封装,将算法的责任和算法本身分割开,交给不同的对象管理。使用算法的上下文环境类中,针对抽象的策略类进行编程。符合依赖倒转原则,并且出现了新的算法时,只需要增加一个新的实现即可。

  • **策略(Strategy) **定义所有⽀持算法的公共接⼝。 Context 使⽤这个接⼝来调⽤某 ConcreteStrategy 定义的算法。
  • **策略实现(ConcreteStrategy) **实现了Strategy 接⼝的具体算法
  • **上下⽂环境(Context) **维护⼀个 Strategy 对象的引⽤,⽤⼀个 ConcreteStrategy 对象来装配可定义⼀个接⼝⽅法让 Strategy 访问它的数据

UML类图

基础案例

针对不同商品的打折算法,在引入策略模式前,由一个算法类的方法维护,包含大量的条件转移,并且也不利于维护。
代码下载:strategy.zip

引入策略模式

引入策略模式前,不同的打折算法的计算过程存在的问题。

  1. 有多重条件选择语句,代码混乱
  2. 不同的算法没有办法进行在别处复用
  3. 新增算法的话,需要修改原来的代码,不符合开闭原则。
package behavioralPattern.strategy;import java.text.MessageFormat;/*** 引入策略模式前,不同的打折算法的计算过程* 1.有多重条件选择语句,代码混乱* 2.不同的算法没有办法进行在别处复用* 3.新增算法的话,需要修改原来的代码,不符合开闭原则。** @author liuyp* @date 2022/09/25*/
public class BuyGoods {private String goods;private double price;private double finalPrice;private String desc;public BuyGoods(String goods, double price) {this.goods = goods;this.price = price;}public double calculate(String discountType) {if ("discount85".equals(discountType)) {finalPrice = price * 0.85;desc = "该商品可享受8.5折优惠";} else if ("discount6".equals(discountType)) {finalPrice = price * 0.6;desc = "该商品可享受6折优惠";} else if ("return5".equals(discountType)) {finalPrice = price >= 5 ? price - 5 : 0;desc = "该商品可返现5元";} else {finalPrice = price;desc = "对不起,该商品不参与优惠活动";}System.out.println(MessageFormat.format("您购买的商品为:{0},原价为: {1},{2},最终售卖价格为:{3}", goods, price, desc, finalPrice));return finalPrice;}
}

引入策略模式

修改步骤

  1. 策略: 引入抽象类,所有的价格计算算法实现该抽象类。
  2. 策略实现:针对原有的if else中的价格计算算法,分别在一个个具体的策略实现类中进行实现。
  3. 环境类:购买商品的类中,只需要维护一个策略抽象类的引用即可,传入不通风策略实现,即可实现不同的打折策略。

抽象打折策略

/*** 策略模式中,对策略的抽象层。* 抽象出了公共的描述、价格属性。* 定义了需要子类实现的,具体的打折策略方法。** @author StoneYu* @date 2022/09/25*/
public abstract class AbstractDiscount {protected double finalPrice;protected String desc;public AbstractDiscount(String desc) {this.desc = desc;}public double getFinalPrice() {return finalPrice;}public void setFinalPrice(double finalPrice) {this.finalPrice = finalPrice;}public String getDesc() {return desc;}public void setDesc(String desc) {this.desc = desc;}public abstract double discount(double price);
}

拆分各个打折策略的实现

public class Discount6 extends AbstractDiscount {public Discount6() {super("该商品可享受6折优惠");}@Overridepublic double discount(double price) {finalPrice = price * 0.6;return finalPrice;}
}public class Discount85 extends AbstractDiscount {public Discount85() {super("该商品可享受8.5折优惠");}@Overridepublic double discount(double price) {finalPrice = price * 0.85;return finalPrice;}
}public class NoDiscount extends AbstractDiscount {public NoDiscount() {super("对不起,该商品不参与优惠活动");}@Overridepublic double discount(double price) {finalPrice = price;return finalPrice;}
}public class Return5 extends AbstractDiscount {public Return5() {super("该商品可返现5元");}@Overridepublic double discount(double price) {this.finalPrice = price >= 5 ? price - 5 : 0;return finalPrice;}
}

修改环境类,只需要维护策略的引用

/*** 策略模式-环境类* 使用策略模式优化后的购买商品的方法* 1.没有了各种if-else* 2.不需要关注算法的具体实现,只需要维护一个策略的抽象类引用。符合依赖倒转原则** @author StoneYu* @date 2022/09/25*/
public class BuyGoods {private String goods;private double price;private AbstractDiscount abstractDiscount;public BuyGoods(String goods, double price, AbstractDiscountabstractDiscount) {this.goods = goods;this.price = price;this.abstractDiscount = abstractDiscount;}public double calculate() {double finalPrice = abstractDiscount.discount(this.price);String desc = abstractDiscount.getDesc();System.out.println(MessageFormat.format("商品:{0},原价:{1},{2},最 终价格为:{3}", goods, price, desc, finalPrice));return finalPrice;}
}

Spring中实践

新建策略接口

public interface DiscountStratege {/*** 折扣方法*/void discount();}

具体的策略 1

/*** 具体策略实现1** @author LiuYuping* @date 2024/03/14 15:14*/
@Component
public class FullReductionDiscountStratege implements DiscountStratege{@Overridepublic void discount() {System.out.println("满减策略,满一百减100");}
}

具体策略 2

/*** 具体策略实现2** @author LiuYuping* @date 2024/03/14 15:15*/
@Component
public class WeekDayDiscountStratege implements DiscountStratege{@Overridepublic void discount() {System.out.println("这里是周末满减策略");}
}

策略枚举,保存所有策略名称

public enum DiscountStrategeEnum {WEEK_DAY_STRATEGE("fullReductionDiscountStratege","满一百减一百"),FULL_REDUCTION("weekDayDiscountStratege","周末满减策略");String concernedStrategeBeanId;String strategeName;DiscountStrategeEnum(String concernedStrategeBeanId, String strategeName) {this.concernedStrategeBeanId = concernedStrategeBeanId;this.strategeName = strategeName;}public String getConcernedStrategeBeanId() {return concernedStrategeBeanId;}public String getStrategeName() {return strategeName;}
}

策略 Context 保存所有策略 Bean 示例

@Service
public class DiscountStrategeContext {@Autowiredprivate Map<String,DiscountStratege> allDiscountStrategeMap;/*** 获取指定的策略** @param discountStrategeEnum 折扣策略枚举* @return {@link DiscountStratege}*/public DiscountStratege getStratege(DiscountStrategeEnum discountStrategeEnum){return allDiscountStrategeMap.get(discountStrategeEnum.getConcernedStrategeBeanId());}}

用例

在需要使用策略的地方,按需注入指定类型的策略对象,新增策略时不需要修改原有代码

@SpringBootTest
class DemoApplicationTests {@AutowiredDiscountStrategeContext discountStrategeContext;@Testvoid testDiscountStratege() {DiscountStratege stratege = discountStrategeContext.getStratege(DiscountStrategeEnum.WEEK_DAY_STRATEGE);stratege.discount();}}

http://www.ppmy.cn/news/1469517.html

相关文章

设计模式:从接口的角度切入静态工厂模式

面向接口编程的意义 所谓面向接口去编程的核心含义就是为了——“封装隔离” 通常的封装&#xff0c;是指对数据结构的封装&#xff0c;将几种数据类型整到一块&#xff0c;组成一个新的数据类型&#xff1b;而java中的封装&#xff0c;包含对数据和行为进行抽象&#xff0c;…

重新学习STM32(1)GPIO

概念简介 GPIO 是通用输入输出端口的简称&#xff0c;简单来说就是 STM32 可控制的引脚。STM32 芯片通过 GPIO 引脚与外部设备连接起来&#xff0c;从而实现与外部通讯、控制以及数据采集的功能。 GPIO被分成很多组&#xff0c;比如 GPIOA和GPIOB等。所有的 GPIO引脚都有基本的…

数据结构-3、栈、队列和数组

3.1、栈 3.1.1、栈的基本概念&#xff1a; 1、栈的定义&#xff1a; ​ 栈是只允许在一端进行插入或删除操作的线性表。首先&#xff0c;栈是一种线性表&#xff0c;但限定这种线性表只能在某一端进行插入和删除操作&#xff0c;如下图&#xff1a; ​ 栈顶&#xff08;Top&…

关闭kylin(麒麟)系统的安全认证(烦人的安全认证)

打开grub sudo vim /etc/default/grup修改安全认证选项 增加12行&#xff0c;把13行注释掉 保存更改, 然后执行下面的命令&#xff1a; sudo sync sudo reboot重启成功后&#xff0c;就关闭了安全认证了~~~~~。 总体来讲&#xff0c;kylin还是基于ubuntu的内核的&#xff0c;…

springboot事务失效场景有哪些

1、方法未被声明为事务 在Spring Boot中&#xff0c;事务是基于注解或XML配置的方式进行声明的。如果一个方法没有被声明为事务&#xff0c;那么其中的数据库操作将不会受到事务管理的影响&#xff0c;可能导致数据不一致的问题。 2、异常未被抛出 在默认情况下&#xff0c;…

二手物品交易系统的设计

管理员账户功能包括&#xff1a;系统首页&#xff0c;个人中心&#xff0c;管理员管理&#xff0c;商家管理&#xff0c;用户管理&#xff0c;商品管理&#xff0c;用户咨询管理 商家账户功能包括&#xff1a;系统首页&#xff0c;个人中心&#xff0c;商品管理&#xff0c;用…

统计信号处理基础 习题解答10-16

题目&#xff1a; 对于例10.1&#xff0c;证明由观察数据得到的信息是&#xff1a; 解答&#xff1a; 基于习题10-15的结论&#xff0c;&#xff0c;那么&#xff1a; 而根据习题10-15的结论&#xff1a; 此条件概率也是高斯分布&#xff0c;即&#xff1a; 根据相同的计算&a…

(done) 什么是 perplexity 困惑度?

参考&#xff1a;https://www.youtube.com/watch?vB_2bntDYano 困惑度 perplexity 是一种用来衡量语言模型性能的度量&#xff0c;类似于交叉熵。 困惑度越低越好&#xff0c;越低说明一个模型越好。 一个典型的公式在下面&#xff1a;