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_Q51100828520 小时前
python+django/flask的篮球馆/足球场地/运动场地预约系统
spring boot·python·django·flask·node.js·php
Q_Q51100828521 小时前
python+django/flask的城市供水管网爆管预警系统-数据可视化
spring boot·python·django·flask·node.js·php
JosieBook1 天前
【SpringBoot】31 核心功能 - 单元测试 - JUnit5 单元测试中的断言机制——验证你的代码是否按预期执行了
spring boot·单元测试·log4j
计算机学姐1 天前
基于SpringBoot的高校社团管理系统【协同过滤推荐算法+数据可视化】
java·vue.js·spring boot·后端·mysql·信息可视化·推荐算法
编啊编程啊程1 天前
【029】智能停车计费系统
java·数据库·spring boot·spring·spring cloud·kafka
hashiqimiya1 天前
springboot后端的接口headers
java·spring boot·后端
ss2731 天前
Springboot + vue 医院管理系统
vue.js·spring boot·后端
披着羊皮不是狼1 天前
Spring Boot——从零开始写一个接口:项目构建 + 分层实战
java·spring boot·后端·分层
Spirit_NKlaus1 天前
Springboot自定义配置解密处理器
java·spring boot·后端