springBoot中的观察者模式实现

pringBoot中的观察者模式实现

什么是观察者模式?假设你要打一局酣畅淋漓的游戏,那么你可能需要进行以下操作->

1. 解锁手机屏幕 2. 找到你要进行游戏的位置 3. 单机启动游戏

现在我们将启动游戏设计为一个api接口

控制器类 -> 三个业务方法均为控制台打印日志

package com.example.demo.Controller;
import com.example.demo.service.GameService;
import com.example.demo.service.GameServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
//自动将返回值转换为json返回
@RestController
public class GameController {
   
    @Autowired
    GameServiceImpl gameService;
    @GetMapping("startGame")
    public String startGame() {
   
//        调用业务逻辑
        gameService.publisher();
        return "游戏,启动!";
    }
}

访问接口 ->
在这里插入图片描述

可以看到,在同一个api接口的业务逻辑下,我们先后执行了三个不同的方法,虽然也可以完成业务逻辑,但是不利于代码维护。例如我们添加一个在游戏前希望先弹出一个窗口,询问用户是否进行游戏,那么我们则需要新增一个业务方法,然后在接口添加该方法。违反了设计原则中的开闭原则,且代码间是紧密耦合的。

  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot观察者模式被广泛应用于事件驱动的编程模型。Spring Boot通过使用事件和监听器来实现观察者模式,以实现对象之间的解耦和通信。 在Spring Boot,事件是一个特殊的对象,它封装了与应用程序相关的状态信息。当某个特定的事件发生时,Spring Boot会自动通知所有注册的监听器,并将事件对象传递给它们。监听器可以根据事件的类型和内容来执行相应的操作。 下面是一个简单的示例,演示了如何在Spring Boot使用观察者模式: 1. 创建一个事件类,例如`MyEvent`,用于封装事件的相关信息。 2. 创建一个监听器类,例如`MyEventListener`,实现`ApplicationListener`接口,并指定要监听的事件类型。 ```java import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; @Component public class MyEventListener implements ApplicationListener<MyEvent> { @Override public void onApplicationEvent(MyEvent event) { // 处理事件 System.out.println("Received event: " + event.getMessage()); } } ``` 3. 在需要触发事件的地方,使用`ApplicationEventPublisher`接口的实现类来发布事件。 ```java import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Component; @Component public class MyEventPublisher { private final ApplicationEventPublisher eventPublisher; public MyEventPublisher(ApplicationEventPublisher eventPublisher) { this.eventPublisher = eventPublisher; } public void publishEvent(String message) { // 创建事件对象 MyEvent event = new MyEvent(message); // 发布事件 eventPublisher.publishEvent(event); } } ``` 通过以上步骤,我们就可以在Spring Boot使用观察者模式了。当`MyEventPublisher`发布事件时,`MyEventListener`会自动接收到事件并执行相应的操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值