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 类使用了策略模式,可以根据需求选择不同的支付方式。

相关推荐
Wild_Pointer.24 分钟前
设计模式实战精讲:全景目录
设计模式·设计规范
Victor35626 分钟前
Redis(129)Redis的字典(Dictionary)是如何实现的?
后端
Victor35629 分钟前
Redis(128)Redis的跳表(Skip List)是如何实现的?
后端
q***92517 小时前
Spring Cloud Data Flow 简介
后端·spring·spring cloud
m0_639817158 小时前
基于springboot火锅店管理系统【带源码和文档】
java·spring boot·后端
会编程的林俊杰8 小时前
SpringBoot项目启动时的依赖处理
java·spring boot·后端
码事漫谈9 小时前
C++循环结构探微:深入理解while与do...while
后端
李慕婉学姐9 小时前
【开题答辩过程】以《Javaweb的火花流浪动物救助系统设计与实现》为例,不会开题答辩的可以进来看看
vue.js·spring boot·mysql
q***72879 小时前
SpringBoot中整合RabbitMQ(测试+部署上线 最完整)
spring boot·rabbitmq·java-rabbitmq
一叶飘零_sweeeet9 小时前
深度拆解汽车制造系统设计:用 Java + 设计模式打造高扩展性品牌 - 车型动态生成架构
java·设计模式·工厂设计模式