设计模式-策略模式

作者: 京东工业 孙磊

一、概念

策略模式(Strategy Pattern)也称为(Policy Parttern)。 它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变换,不会影响到使用算法的客户。策略模式属性行为模式。

策略模式结构图
在这里插入图片描述

二、实际应用

业务场景:业务需要监听多种消息,将接收到的消息更新到同一个ES中,不同的消息类型使用不同的策略处理,补充不同的数据信息,更新到ES中,供商家搜索和统计使用。

代码实现结合spring框架、简单工厂和策略模式一起使用。

1public interface GatherExecuteService { 2 /** 3 * 处理消息体 4 * 5 * @param gatherDataVo 6 */ 7 boolean execute(GatherDataVo gatherDataVo); 8}

多个实现类

1// 价格策略实现 2@Service 3public class PriceExecuteServiceImpl implements GatherExecuteService { 4 @Override 5 public boolean execute(GatherDataVo gatherDataVo) { 6 .....具体实现代码省略 7 } 8}
<!---->
1// 商品策略实现 2@Service 3public class ProductExecuteServiceImpl implements GatherExecuteService { 4 5 @Override 6 public boolean execute(GatherDataVo gatherDataVo) { 7 8 .....具体实现代码省略 9 } 10}
<!---->
1// 库存策略实现 2@Service 3public class StockExecuteServiceImpl implements GatherExecuteService { 4 @Override 5 public boolean execute(GatherDataVo gatherDataVo) { 6 .....具体实现代码省略 7 8 } 9}

使用枚举存储策略实现bean

1@Getter 2@AllArgsConstructor 3public enum MessageTypeEnum { 4 PRODUCT(0, "productExecuteServiceImpl", "商品基本信息消息"), 5 PRICE(1, "priceExecuteServiceImpl", "价格消息"), 6 STOCK(2, "stockExecuteServiceImpl", "库存消息") ; 7 private int type; 8 private String service; 9 private String description; 10 public static String getServiceName(int type) { 11 MessageTypeEnum[] typeEnums = MessageTypeEnum.values(); 12 for (MessageTypeEnum enumType : typeEnums) { 13 if (enumType.getType() == type) { 14 return enumType.getService(); 15 } 16 } 17 return null; 18 } 19}

使用到不同策略的代码

1// 根据消息类型获取不同策略类,然后使用spring的ApplicationContext获取bean,达到执行不同策略的目的。 2String serviceName = MessageTypeEnum.getServiceName(gatherDataVo.getMessageType()); 3if (StringUtils.isNotBlank(serviceName)) { 4 GatherExecuteService gatherExecuteService = (GatherExecuteService) SpringContextUtil.getBean(serviceName, GatherExecuteService.class); 5}

策略模式是一种比较简单的设计模式,工作中经常和其他设计模式一块使用。简单的应用记录分享一下。

点赞
收藏

评论区

加载中...

相关推荐

责任链和策略设计模式-基于Java编程语言

责任链和策略设计模式这两种设计模式非常实用,下面简单介绍一下我对这两种设计模式的理解和它们在Spring框架源码中的应用。

Vue 骚技巧,策略模式实现动态表单验证

!(https://oscimg.oschina.net/oscnet/5e0568a314054f2d995c1562bda18f70.png)策略模式(StrategyPattern)又称政策模式,其定义一系列的算法,把它们一个个封装起来,并且使它们可以互相替换。封装的策略算法一般是独立的,策略模式根据输入来调整采用哪个算法。

Java设计模式

一、策略模式(让算法与对象独立)    策略模式定义了算法族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。!(http://static.oschina.net/uploads/space/2016/1108/180244_oYm8_1789589.png)二、观察者模式(让你的对象知悉现状) 

Java 设计模式系列(十二)策略模式(Strategy)

Java设计模式系列(十二)策略模式(Strategy)策略模式属于对象的行为模式。其用意是针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。一、策略模式的结构策略模式是对算

Java描述设计模式(22):策略模式

本文源码:GitHub·点这里(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fgithub.com%2Fcicadasmile%2Fmodelarithmeticparent)||GitEE·点这里(https://gitee.com/cicadasmile/modela

如何利用策略模式避免冗长的 if

策略模式。在实际的项目开发中,这个模式也比较常用。最常见的应用场景是,利用它来避免冗长的ifelse或switch分支判断。不过,它的作用还不止如此。它也可以像模板模式那样,提供框架的扩展点等等。对于策略模式。本篇我们讲解策略模式的原理和实现,以及如何用它来避免分支判断逻辑。后续我会通过一个具体的例子,来详细讲解策略模式的应用场景以及真正的设计意图