基于注解实现的策略模式,步骤简单,通俗易懂!

1,413 阅读2分钟

背景

在项目开发的过程中,我们经常会遇到如下的一种场景:对于用户的请求需要根据不同的情况进行不同的处理。

  • 最简单粗暴的一种处理方式是使用switch…case或者if…else。但是这样处理方式只适用于处理逻辑简单或者情况分类较少的情况,如学校发放校服,男同学发放男士衣服,女同学发放女士衣服。
  • 但是,如果处理逻辑毕竟复杂,或者情况分类较多,甚至未来有可能增加情况分类,上一种处理方式就会显得力不从心。此时使用策略模式将会是一种更优的处理方式。

基础配置&步骤

以下的方案是基于注解实现的策略模式。基础步骤&配置如下:

  • 定义策略名称:该项使用枚举实现
  • 定义策略名称注解:使用注解进行定义
  • 定义策略行为接口:该接口定义了策略行为
  • 定义策略处理器:包含策略名称的注解,并实现了策略行为接口
  • 定义策略容器:此处使用map作为策略容器,key为策略名称注解,value为策略处理器的实例
  • 初始化策略:容器初始化时候,从容器中读取包含策略名称注解的实例,并将其放入到策略容器中。

代码实现

在以下的例子中,会针对用户请求的Msg进行解析,msgType有两种:一种是聊天消息ChatMsg,还有一种是系统消息SysMsg。实现方式如下所示:

定义策略名称

public enum MsgType {

    CHAT_MSG,
    SYS_MSG;
}

定义策略名称注解

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Type {
    MsgType value();
}

定义策略行为接口

public interface BaseMsgHandler {
    void handleMsg(String content);
}

定义策略处理器

@Component
@Type(value = MsgType.CHAT_MSG)
public class ChatMsgHandler implements BaseMsgHandler{

    @Override
    public void handleMsg(String msg) {
        System.out.println("This is chatMsg. Detail msg information is :" + msg);
    }
}

@Component
@Type(value = MsgType.SYS_MSG)
public class SysMsgHandler implements BaseMsgHandler{

    @Override
    public void handleMsg(String msg) {
        System.out.println("This is sysMsg. Detail msg information is :" + msg);
    }
}

定义策略容器

public static final Map<Type, BaseMsgHandler> msgStrategyMap = new HashMap<>();

初始化策略

@Component
public class MsgConfig implements ApplicationContextAware {

    public static final Map<Type, BaseMsgHandler> msgStrategyMap = new HashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        applicationContext.getBeansWithAnnotation(Type.class).entrySet().iterator().forEachRemaining(entrySet ->{
            msgStrategyMap.put(entrySet.getKey().getClass().getAnnotation(Type.class),
                    (BaseMsgHandler) entrySet.getValue());
        });
    }
}

上述准备动作完成后,就可以编写调用代码了:

import lombok.Data;

@Data
public class Msg{
	private String content;
	private MsgType msgType;
}

@RestController
@RequestMapping("/")
public class MsgController {

    @RequestMapping("msg")
    public void handleMsg(@RequestBody Msg msg){
        BaseMsgHandler handler = MsgConfig.msgStrategyMap.get(msg.getMsgType());
        handler.handleMsg(msg.getContent());
    }
}

最后

欢迎关注公众号:前程有光,领取一线大厂Java面试题总结+各知识点学习思维导+一份300页pdf文档的Java核心知识点总结!