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

相关推荐
.生产的驴9 分钟前
SpringBoot 封装统一API返回格式对象 标准化开发 请求封装 统一格式处理
java·数据库·spring boot·后端·spring·eclipse·maven
景天科技苑17 分钟前
【Rust】Rust中的枚举与模式匹配,原理解析与应用实战
开发语言·后端·rust·match·enum·枚举与模式匹配·rust枚举与模式匹配
晨集18 分钟前
Uni-App 多端电子合同开源项目介绍
java·spring boot·uni-app·电子合同
时间之城21 分钟前
笔记:记一次使用EasyExcel重写convertToExcelData方法无法读取@ExcelDictFormat注解的问题(已解决)
java·spring boot·笔记·spring·excel
追逐时光者1 小时前
MongoDB从入门到实战之Docker快速安装MongoDB
后端·mongodb
方圆想当图灵1 小时前
深入理解 AOP:使用 AspectJ 实现对 Maven 依赖中 Jar 包类的织入
后端·maven
豌豆花下猫1 小时前
Python 潮流周刊#99:如何在生产环境中运行 Python?(摘要)
后端·python·ai
嘻嘻嘻嘻嘻嘻ys1 小时前
《Spring Boot 3 + Java 17:响应式云原生架构深度实践与范式革新》
前端·后端
异常君1 小时前
线程池隐患解析:为何阿里巴巴拒绝 Executors
java·后端·代码规范
mazhimazhi1 小时前
GC垃圾收集时,居然还有用户线程在奔跑
后端·面试