Spring Boot中策略模式结合依赖注入的实现方式

在Spring Boot项目开发中,常常会遇到根据不同的业务场景执行不同逻辑的需求,策略模式就是一种很好的设计模式来应对这种情况。同时,Spring Boot强大的依赖注入机制可以方便地将不同的策略类进行管理和调用。

1. 定义策略接口

定义一个策略接口,所有具体的策略类都将实现这个接口:

java 复制代码
public interface BaseStrategy {
    void handle(String request);
}

2. 实现具体的策略

实现几个具体的策略类,例如处理订单和支付:

java 复制代码
@Component("order")
@Slf4j
public class OrderStrategy implements BaseStrategy {

    @Override
    public void handle(String request) {
        System.out.println("下单成功" + request);
    }
}

@Component("pay")
@Slf4j
public class PayStrategy implements BaseStrategy {

    @Override
    public void handle(String request) {
        System.out.println("支付成功" + request);
    }
}

也可以通过配置类的方式注入策略模式实现类,先注释其中的@Component注解

java 复制代码
@Configuration
public class HandlerConfig {

    @Bean("order")
    public BaseStrategy handleOrder() {
       return new OrderStrategy();
    }

    @Bean("pay")
    public BaseStrategy handlePay() {
        return new PayStrategy();
    }
}

3. 创建策略工厂

为了方便获取不同的策略,我们可以创建一个工厂类 BaseFactory,它将通过依赖注入管理策略的实例,并提供获取策略的功能。

java 复制代码
@Component
@Slf4j
public class BaseFactory {

    @Resource
    private Map<String, BaseStrategy> handlerMap;

    public BaseStrategy getHandler(String type) {
        return handlerMap.getOrDefault(type, (request) -> {
            log.error("Unknown request type: " + type);
        });
    }
}

在这个类中,我们使用 @Resource 注解注入了一个 Map<String, BaseStrategy>,这个 Map 将所有注册的策略按名称存储起来。通过策略名称,我们可以从 Map 中获取到对应的策略对象。

4. 使用策略工厂处理请求

java 复制代码
@RestController
@RequestMapping("base")
@Slf4j
public class BaseController {

    @Resource
    private BaseFactory baseFactory;

    @GetMapping("/getHandler")
    public ResponseEntity<String> getHandler(@RequestParam String type, @RequestParam String message) {
        BaseStrategy handler = baseFactory.getHandler(type);
        if (handler != null) {
            handler.handle(message);
            return ResponseEntity.ok("操作已执行: " + type);
        } else {
            return ResponseEntity.badRequest().body("策略类型不存在: " + type);
        }
    }
}
相关推荐
Q_Q5110082851 小时前
python+uniapp基于微信小程序的旅游信息系统
spring boot·python·微信小程序·django·flask·uni-app·node.js
Q_Q5110082851 小时前
python基于web的汽车班车车票管理系统/火车票预订系统/高铁预定系统 可在线选座
spring boot·python·django·flask·node.js·汽车·php
DokiDoki之父3 小时前
MyBatis—增删查改操作
java·spring boot·mybatis
摇滚侠4 小时前
Spring Boot 项目, idea 控制台日志设置彩色
java·spring boot·intellij-idea
Code blocks6 小时前
GB28181视频服务wvp部署(一)
java·spring boot·后端
我命由我123456 小时前
Spring Boot - Spring Boot 静态资源延迟响应(使用拦截器、使用过滤器、使用 ResourceResolver)
java·spring boot·后端·spring·java-ee·intellij-idea·intellij idea
xiangzhihong88 小时前
Spring Boot集成SSE实现AI对话的流式响应
人工智能·spring boot
ʚ希希ɞ ྀ9 小时前
SpringBoot的学习
java·spring boot·学习
linweidong10 小时前
理想汽车Java后台开发面试题及参考答案(下)
jvm·spring boot·spring cloud·rpc·虚拟机·feign·二叉树排序
Q_Q51100828511 小时前
python+django/flask婚纱摄影拍照管理系统
spring boot·python·django·flask·node.js·php