• 基于注解实现的策略模式


    代码实现

    在以下的例子中,会针对用户请求的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

  • 相关阅读:
    sizeof和strlen区别
    Reverse Words in a String
    删除字符串中重复的字符
    Reverse String
    数组中一个数字出现的次数超过了数组长度的一半,请找出这个数
    输出数组中大于等于左边所有数且小于等于右边所有数的元素
    java获取数据库里表的名字
    [转]C++编写Config类读取配置文件
    c# App.Config详解
    pitch yaw roll是什么
  • 原文地址:https://www.cnblogs.com/fanfuhu/p/16054426.html
Copyright © 2020-2023  润新知