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

相关推荐
MY_TEUCK1 小时前
【Java 后端】SpringBoot 登录认证与会话跟踪实战(JWT + Filter/Interceptor)
java·开发语言·spring boot
计算机程序定制辅导1 小时前
计算机小程序毕设实战-基于Spring Boot与微信小程序的考研资源共享平台设计与实现基于springboot+微信小程序的考研复习辅助平台【完整源码+LW+部署说明+演示视频,全bao一条龙等】
spring boot·微信小程序·小程序·课程设计
程序员飞哥3 小时前
重构 AI 思维(一):Prompt Engineering,如何下达不可违抗的指令?
人工智能·后端
皮皮林5514 小时前
@Autowired 和 @Resource 注解有啥区别?你这项目怎么还混着用呢?
后端
ximu_polaris4 小时前
设计模式(C++)-行为型模式-中介者模式
c++·设计模式·中介者模式
程序员小假5 小时前
HTTP3 性能更好,为什么内网微服务依然多用 HTTP2?HTTP2 内网优势是什么?
java·后端
wangbing11255 小时前
踩坑:el8应用装在el9上
开发语言·后端·ruby
kyriewen116 小时前
你等的Babel编译,够喝三杯咖啡了——用Rust重写的SWC,只需眨个眼
开发语言·前端·javascript·后端·性能优化·rust·前端框架
IT_陈寒6 小时前
SpringBoot自动配置坑了我,原来要这样绕过去
前端·人工智能·后端
东方小月6 小时前
Claude Code 完整上手指南:MCP、Skills、第三方模型配置一次搞定
前端·人工智能·后端