spring中策略模式使用

策略模式

工作中经常使用到策略模式+工厂模式,实现一个接口多种实现的灵活调用与后续代码的扩展性。在spring中使用策略模式更为简单,所有的bean均为spring容器管理,只需获取该接口的所有实现类即可。

下面以事件处理功能为例,接收到事件之后,根据事件类型调用不同的实现接口去处理。如需新增事件,只需扩展实现类即可,无需改动之前的代码。这样即做到了功能的隔离,又可防止改动原代码导致的bug。

类图

代码示例

定义接口

1public interface IBaseEventService { 2 3 /** 4 * 处理事件 5 * @param eventObject 6 * @return 7 * @throws Exception 8 */ 9 public boolean dealEvent(String eventObject); 10 11 /** 12 * 获取事件类型 13 * @return 14 */ 15 public String getType(); 16 17}

接口实现

1@Service 2public class AddUserEventServiceImpl implements IBaseEventService { 3 @Override 4 public boolean dealEvent(String eventObject) { 5 // TODO 业务处理逻辑 6 return false; 7 } 8 9 @Override 10 public String getType() { 11 return EventTypeEnum.ADD_USER_AFTER.getKey(); 12 } 13} 14

常量定义

1public enum EventTypeEnum { 2 ADD_USER_AFTER("ADD_USER_AFTER"), 3 PLACE_ORDER_AFTER("PLACE_ORDER_AFTER"); 4 5 private String key; 6 7 EventTypeEnum(String key) { 8 this.key = key; 9 } 10 11 public String getKey() { 12 return key; 13 } 14 15 public void setKey(String key) { 16 this.key = key; 17 } 18}

策略类

1@Service 2public class EventStrategyService { 3 4 Map<String, IBaseEventService> eventServiceMap = new HashMap<>(); 5 6 /** 7 * 构造函数 8 * @param eventServices spring容器中所有IBaseEventService的实现类 9 */ 10 public EventStrategyService(List<IBaseEventService> eventServices) { 11 for (IBaseEventService eventService : eventServices) { 12 eventServiceMap.put(eventService.getType(), eventService); 13 } 14 } 15 16 /** 17 * 根据事件类型调用不同的实现类处理 18 */ 19 public boolean dealEvent(String eventType, String eventObject) { 20 IBaseEventService eventService = eventServiceMap.get(eventType); 21 if (eventService == null){ 22 throw new BizException("未找到事件处理实现类,eventType:" + eventType); 23 } 24 return eventService.dealEvent(eventObject); 25 } 26 27}

接口调用

1 @Autowired 2 private EventStrategyService eventStrategyService; 3 4 //处理事件 5 eventStrategyService.dealEvent(eventType, userObject);
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )

Event Bus 之 Otto(一)

Otto是EventBus模式的一种实现,使用它可以使事件的发送与处理解耦,为了坚挺某个事件不必再去实现相应的接口,只需简单的加标注、注册就可以实现。标注:首先来看两种标注:subscribe:@Retention(RetentionPolicy.RUNTIME)@Target(ElementTyp

Spring中的设计模式

spring在容器中使用了观察者模式:一、spring事件:ApplicationEvent,该抽象类继承了EventObject类,jdk建议所有的事件都应该继承自EventObject。二、spring事件监听器:ApplicationLisener,该接口继承了EventListener接口,jdk建议所有的事件监听器都应该继承Ev