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