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

相关推荐
高频因子挖掘机3 分钟前
盘中筛选要同时看价格和盘口?按需分层比“一次全拿”更好维护
后端·github·api
asong8 分钟前
从写代码到部署上线,Cloudflare 给 AI 配了一把新钥匙
前端·javascript·后端
卷无止境9 分钟前
当AI写代码遇见Rust为什么会卡壳
后端·python
Percy_kk12 分钟前
Django的CRUD映射
后端·django
用户EasyAdminBlazor14 分钟前
Blazor Server 性能优化实战:Circuit、数据库、Redis 与并发
后端
王中阳Go18 分钟前
Agent 第一句就 500,我们查了三轮:入口日志少打了一个参数
后端·agent·ai编程
羑悻18 分钟前
穿越Docker内核迷雾:揭秘镜像分层存储的叠加态与卷挂载的多维空间穿梭技术
后端·docker·容器
励志不掉头发的内向程序员19 分钟前
从鼠标点击到画出一条线:CAD 交互层的状态机设计
后端·架构
用户EasyAdminBlazor25 分钟前
EasyAdminBlazor 日志系统源码解析:为什么数据库日志需要有界队列?
后端
Sylven26 分钟前
【DevOps 开发流程】问题+标签驱动开发,可视化你和AI的开发进度
后端