责任链模式就是把所有的接口都构成一个链条,通过处理器程序来调用所有的链条,防止接口耦合
我们来实现注册的功能,一个注册调用链用于注册,一个短信调用链用于发送短信
两个调用链互相不干扰,注册成功后,2个接口都会执行
定义注册接口
public interface ZhuCeService {
public boolean zhuce(String user);
}
创建注册链条 先执行,实现注册接口
package com.example.demo.service.impl;
import com.example.demo.service.ZhuCeService;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
/**
*
* 注册调用链
* @param
* @return
* @throws Exception
*/
@Order(1)
@Service
public class ZhuCeChain implements ZhuCeService {
@Override
public boolean zhuce(String user) {
if(user==null){
return false;
}
System.out.println("注册成功");
return true;
}
}
创建短信链条,后执行,实现注册接口
package com.example.demo.service.impl;
import com.example.demo.service.ZhuCeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import java.util.List;
//根据order来指定谁先执行
@Order(2)
@Service
public class DuanXinChain implements ZhuCeService {
@Override
public boolean zhuce(String user) {
if(user==null){
return false;
}
System.out.println("发送短信成功");
return true;
}
}
创建注册的处理程序,调用所有的链条
package com.example.demo.config;
import com.example.demo.service.ZhuCeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
/**
*
* 注册处理器
* @param
* @return
* @throws Exception
*/
@Component
public class ZhuCeHandler {
@Autowired
private List<ZhuCeService> zhuCeServices;
/**
*
* 处理链条上所有的接口调用
* @param
* @return
* @throws Exception
*/
public void handler(String user){
for (ZhuCeService x : zhuCeServices) {
boolean flag= x.zhuce(user);
if(!flag){
//如果链条上有一个接口 失败了 那么直接停止
break;
}
}
}
}
控制层 调用注册处理程序
package com.example.demo.controller;
import com.example.demo.config.ZhuCeHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ZhuCeController {
@Autowired
private ZhuCeHandler zhuCeHandler;
@GetMapping("/zhuce")
public String zhuce(){
//调用注册处理器
zhuCeHandler.handler("123");
return "注册成功";
}
}