基于注解实现的策略模式
代码实现
在以下的例子中,会针对用户请求的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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!