SpringBoot实现责任链模式

  • Post author:
  • Post category:其他





前言

类似现实生活中铁链,由一个个铁环首尾相接构成一条链,如果这种结构用在编程领域,则每个节点可以看做一个对象,每个对象有不同的处理逻辑,将一个请求从链的首端发出,沿着链的路径依次传递每个节点对象,直到有对象处理这个请求为止。



一、责任链模式简介

责任链模式(Chain of Responsibility Pattern),顾名思义,为请求者和接受者之间创建一条对象处理链路,避免请求发送者与接收者耦合在一起。



二、代码实现

场景:订单支付过程,进行鉴权检验、参数检验、余额检验等等



1.定义一个支付订单表单类

@Data
public class PayOrderForm {

    // token
    private String token;
    // 订单ID
    private String orderId;
    // 金额
    private BigDecimal amount;

}



2.定义一个支付接口

public interface PayOrderService {

    boolean payOrder(PayOrderForm payOrderForm);

}



3.定义责任链节点处理类

通过

@Order

注解对每个节点的执行优先进行排序



3.1鉴权处理

@Order(0)
@Component
public class AuthPayOrderChainFilter implements PayOrderService {

    @Override
    public boolean payOrder(PayOrderForm payOrderForm) {
        if (!"token".equals(payOrderForm.getToken())) {
            System.out.println("token不合法");
            return false;
        }
        return true;
    }

}



3.2参数处理

@Order(1)
@Component
public class ParamsPayOrderChainFilter implements PayOrderService {

    @Override
    public boolean payOrder(PayOrderForm payOrderForm) {
        if (StrUtil.isBlank(payOrderForm.getOrderId())) {
            System.out.println("订单ID不能为空");
            return false;
        }
        if (ObjectUtil.isNull(payOrderForm.getAmount())) {
            System.out.println("金额不能为空");
            return false;
        }
        return true;
    }

}



3.3余额处理

@Order(2)
@Component
public class BalancePayOrderChainFilter implements PayOrderService {

    @Override
    public boolean payOrder(PayOrderForm payOrderForm) {
        // 查询余额
        System.out.println("余额检验通过");
        return true;
    }

}



4.定义责任链处理类

通过

@Autowired

注解注入PayOrderService列表,SpringBoot会自动将实现改接口的类加入列表

@Component
public class PayOrderChainProcessor {

    @Autowired
    private List<PayOrderService> payOrderServices;

    public void handlePayOrder(PayOrderForm payOrderForm) {
        for (PayOrderService payOrderService : payOrderServices) {
            boolean payOrder = payOrderService.payOrder(payOrderForm);
            if (!payOrder) break;
        }
    }

}



5.测试

@Autowired
private PayOrderChainProcessor payOrderChainProcessor;
@Test
public void test() {
	PayOrderForm payOrderForm = new PayOrderForm();
    payOrderChainProcessor.handlePayOrder(payOrderForm);

    System.out.println("=========添加token===========");

    // 添加token
    payOrderForm.setToken("token");
    payOrderChainProcessor.handlePayOrder(payOrderForm);

    System.out.println("==========添加订单ID与金额==========");

    // 添加订单ID与金额
    payOrderForm.setOrderId("order1");
    payOrderForm.setAmount(new BigDecimal(100));
    payOrderChainProcessor.handlePayOrder(payOrderForm);
}

输出:

在这里插入图片描述




总结

多个对象可以处理同一个请求,但具体由哪个对象处理则在运行时动态决定。

在请求处理者不明确的情况下向对个对象中的一个提交一个请求。



版权声明:本文为weixin_51833408原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。