SpringBoot 中常见的设计模式

在 Spring Boot 中,很多设计模式是通过 Spring 框架本身来实现的,但我们也可以在实际开发过程中看到多种设计模式的应用。以下是几个常见的设计模式及其在 Spring Boot 中的应用实例:

1. 单例模式 (Singleton Pattern)

在 Spring 中,大多数 Bean 默认采用单例模式,即整个应用上下文中只有一个实例。

示例:
java 复制代码
@Service
public class MyService {
    public String getMessage() {
        return "Hello, Spring Boot!";
    }
}

在 Spring Boot 中,@Service 注解标记的 MyService 类是一个单例 Bean,意味着无论我们调用多少次,Spring 只会创建一个 MyService 实例并注入。

java 复制代码
@RestController
public class MyController {

    @Autowired
    private MyService myService;

    @GetMapping("/message")
    public String getMessage() {
        return myService.getMessage();
    }
}

2. 工厂模式 (Factory Pattern)

Spring Boot 中经常使用工厂模式来创建对象,尤其是在创建复杂的对象或者需要根据条件选择不同类型的对象时。

示例:
java 复制代码
public interface Vehicle {
    void drive();
}

public class Car implements Vehicle {
    @Override
    public void drive() {
        System.out.println("Driving a car...");
    }
}

public class Bike implements Vehicle {
    @Override
    public void drive() {
        System.out.println("Riding a bike...");
    }
}

@Component
public class VehicleFactory {
    public Vehicle getVehicle(String vehicleType) {
        if (vehicleType.equalsIgnoreCase("car")) {
            return new Car();
        } else if (vehicleType.equalsIgnoreCase("bike")) {
            return new Bike();
        }
        return null;
    }
}

在上面的代码中,VehicleFactory 类充当工厂模式,根据不同的条件返回不同的 Vehicle 实现类。

java 复制代码
@RestController
public class VehicleController {

    @Autowired
    private VehicleFactory vehicleFactory;

    @GetMapping("/drive/{vehicleType}")
    public String drive(@PathVariable String vehicleType) {
        Vehicle vehicle = vehicleFactory.getVehicle(vehicleType);
        if (vehicle != null) {
            vehicle.drive();
            return "Vehicle is driving";
        }
        return "Unknown vehicle type";
    }
}

3. 代理模式 (Proxy Pattern)

在 Spring 中,AOP(面向切面编程)是使用代理模式实现的。Spring AOP 通过创建代理对象来增强目标对象的行为。

示例:
java 复制代码
@Aspect
@Component
public class LoggingAspect {

    @Before("execution(* com.hk.service.*.*(..))")
    public void handler(JoinPoint joinPoint) {
        System.out.println("Executing method: " + joinPoint.getSignature().getName());
    }
}

在上面的代码中,LoggingAspect 使用了 AOP 来创建代理对象,在方法执行前记录日志。这是代理模式的一个应用,通过代理对原始方法的行为进行增强。

4. 模板方法模式 (Template Method Pattern)

Spring 中的 JdbcTemplate 就是一个模板方法模式的经典例子。它提供了一个模板方法,开发者只需实现具体的行为。

示例:
java 复制代码
@Component
public class EmpService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<Emp> getAllEmployees() {
        String sql = "SELECT * FROM emp";
        return jdbcTemplate.query(sql, (rs, rowNum) -> new Employee(rs.getInt("id"), rs.getString("name")));
    }
}

JdbcTemplate 提供了一个标准的操作数据库的流程,而开发者只需要提供具体的 SQL 查询和映射逻辑。

5. 观察者模式 (Observer Pattern)

Spring Event 机制提供了一个很好的观察者模式的实现方式。Spring 允许我们创建自定义事件并在应用中发布和监听这些事件。

示例:
java 复制代码
// 定义事件
public class MyEvent extends ApplicationEvent {
    public MyEvent(Object source) {
        super(source);
    }
    
    public void say(){
        System.out.println("my event");
    }
}

// 发布事件
@Component
public class MyEventPublisher {

    @Autowired
    private ApplicationContext applicationContext;

    public void publishEvent() {
        MyEvent event = new MyEvent(this);
        applicationContext.publishEvent(event);
    }
}

// 监听事件
@Component
public class MyEventListener {

    @EventListener
    public void handleEvent(MyEvent event) {
         event.say();
    }
}

在上面的代码中,我们定义了一个事件 MyEvent,然后在 MyEventPublisher 中发布事件,并在 MyEventListener 中监听事件。这是常见的观察者模式,允许不同的组件响应事件。

6. 策略模式 (Strategy Pattern)

策略模式允许我们定义一系列算法,并将每个算法封装起来。Spring 中常通过接口和实现类来实现策略模式。

示例:
java 复制代码
public interface PaymentStrategy {
    void pay(int amount);
}

public class CreditCardPayment implements PaymentStrategy {
    @Override
    public void pay(int amount) {
        System.out.println("Paid " + amount + " using Credit Card");
    }
}

public class PayPalPayment implements PaymentStrategy {
    @Override
    public void pay(int amount) {
        System.out.println("Paid " + amount + " using PayPal");
    }
}

@Component
public class PaymentService {

    private PaymentStrategy paymentStrategy;

    @Autowired
    public PaymentService(PaymentStrategy paymentStrategy) {
        this.paymentStrategy = paymentStrategy;
    }

    public void processPayment(int amount) {
        paymentStrategy.pay(amount);
    }
}

在上面的代码中,PaymentService 类使用了策略模式,可以根据需求选择不同的支付方式。

相关推荐
疯狂的程序猴1 分钟前
Web 抓包完整实践指南,从浏览器网络调试到底层数据流捕获的全流程方案
后端
Arva .10 分钟前
讲一下 Spring 中用到的设计模式
java·spring·设计模式
喵手19 分钟前
我在openEuler上从零开始构建云原生AI应用
后端
解读玫瑰28 分钟前
WSL+openEuler嵌入式开发实战:交叉编译与QEMU仿真全流程
后端
Stream28 分钟前
加密与签名技术之数字签名算法
后端
程序员爱钓鱼31 分钟前
Node.js 编程实战:理解 Buffer 与 Stream
后端·node.js·trae
用户83562907805135 分钟前
Word 图表自动化:基于 C# 的高效数据可视化方案
后端·c#
火车叼位1 小时前
让 ast-grep 听你的:指定语言解析 Vue/TSX/JSX 全流程
前端·javascript·后端
哈哈老师啊2 小时前
Springboot学生接送服务平台8rzvo(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
VX:Fegn08952 小时前
计算机毕业设计|基于springboot + vue图书商城系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计