责任链可以将发送方和接收方的业务处理逻辑隔离开来,降低耦合,提高代码的可扩展性。比如在订单业务中,接收方处理订单时,需要先校验订单的合法性,然后计算订单的花费,接着校验库存和余额等信息,最后更新数据库。中途如果想要添加或者删除功能,都需要在接收方代码中进行修改。这时就需要责任链来处理中间过程,接收方只需要进行最后的数据库更新即可。

订单类:

@Data
public class OrderPojo {
    //订单编号
    private long num;

    private BigDecimal price;


}

 定义处理器接口:

public interface OrderHandler {
    OrderPojo handle(OrderPojo orderPojo);
}

 定义具体的处理器类

@Order(1)//数字越小,越先执行
@Component
public class FirstHandler implements OrderHandler {
    @Override
    public OrderPojo handle(OrderPojo orderPojo) {
        System.out.println("第一步:校验订单的合法性");
        return orderPojo;
    }
}
@Order(2)
@Component
public class SecondHandler implements OrderHandler {

    @Override
    public OrderPojo handle(OrderPojo orderPojo) {
        System.out.println("第二步:计算花费");
        orderPojo.setPrice(orderPojo.getPrice().subtract(new BigDecimal("1")));
        return orderPojo;
    }
}
@Order(3)
@Component
public class ThirdHandler implements OrderHandler {

    @Override
    public OrderPojo handle(OrderPojo orderPojo) {
        System.out.println("第三步:校验库存和余额");
        return orderPojo;
    }
}

定义拦截器上下文类,由消费方直接调用

@Component
public class OrderContext {
    @Autowired
    private List<OrderHandler> list;//sprig会根据Order注解顺序注入该接口的实现类

    public OrderPojo doInterceptor(OrderPojo orderPojo) {
        for (OrderHandler myInterceptor : list) {
            orderPojo = myInterceptor.handle(orderPojo);
            if (orderPojo == null) return null;
        }
        return orderPojo;
    }
}

消费方代码:

@SpringBootTest
public class Consumer {
    @Autowired
    private OrderContext orderContext;
    @Test
    public void test(){
        OrderPojo orderPojo = new OrderPojo();
        orderPojo.setNum(1L);
        orderPojo.setPrice(new BigDecimal("10.0"));
        System.out.println("orderPojo = " + orderPojo);
        orderPojo = orderContext.doInterceptor(orderPojo);
        System.out.println("orderPojo = " + orderPojo);
    }
}

结果:

        使用责任链模式后,在任何一个步骤中添加操作只需要添加实现类即可,增加了代码的可扩展性。 

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐