基于注解实现的策略模式

代码实现

在以下的例子中,会针对用户请求的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<MsgType, BaseMsgHandler> msgStrategyMap=new HashMap<>();

初始化策略

@Component
public class MsgConfig implements ApplicationContextAware {

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

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        applicationContext.getBeansWithAnnotation(Type.class).entrySet().iterator().forEachRemaining(entrySet ->{
          msgStrategyMap.put(applicationContext.getBean(entrySet.getKey()).getClass().getAnnotation(Type.class).value(),
                (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());
    }
}

参考:https://segmentfault.com/a/1190000038189346

posted @ 2022-03-25 14:14  敲键盘的猫  阅读(179)  评论(0编辑  收藏  举报