1.概述
在我们平时的工作中,填写分布填写数据,比如填入商品的基本信息,所有人信息,明细信息,这种情况就可以使用责任链模式来处理。
2.代码实现
2.1商品对象
public class ProductDto {
private String name;
private String owner;
private String detail;
}
2.2处理器基类
package com.study.chain;
public abstract class IHandler<T> {
private IHandler next;
public void setNext(IHandler next) {
this.next = next;
}
public boolean hasNext() {
return next != null;
}
public abstract Boolean handlerCurrent(T object);
//先处理当前,如果返回为true其还有下一个处理器,则调用下一个处理器。
public void handler(T object){
boolean rtn =handlerCurrent(object);
if(hasNext() && rtn){
next.handler(object);
}
}
}
2.3商品基础信息类
其中 Order 表示类的排序
@Order(1)
@Component
public class ProductBaseHandler extends IHandler<ProductDto> {
@Override
public Boolean handlerCurrent(ProductDto object) {
System.out.println("商品基础校验" + object.getName());
return true;
}
}
2.4商品所有人
@Order(2)
@Component
public class ProductOwnerHandler extends IHandler<ProductDto> {
@Override
public Boolean handlerCurrent(ProductDto object) {
System.err.println("商品拥有者校验" + object.getOwner());
return true;
}
}
2.5商品明细
@Component
@Order(3)
public class ProductDetailHandler extends IHandler<ProductDto> {
@Override
public Boolean handlerCurrent(ProductDto object) {
System.err.println("商品明细信息校验" + object.getDetail());
return true;
}
}
2.6处理器工厂类
public class CommonChainFactory<T> {
public IHandler<T> first;
public CommonChainFactory(List<IHandler<T>> list){
for(int i=0;i<list.size()-1;i++){
list.get(i).setNext(list.get(i+1));
}
first= list.get(0);
}
public void execute(T objectDto){
first.handler(objectDto);
}
}
由于这个是泛型类,需要通过配置类进行实例化。
2.7 配置工厂类
@Configuration
public class FactoryConfig {
@Bean
public CommonChainFactory<ProductDto> productChainFactory(List<IHandler<ProductDto>> list){
return new CommonChainFactory<>(list);
}
}
2.8 使用
@Resource
private CommonChainFactory<ProductDto> productChainFactory;
@GetMapping("/chain")
public void chain() {
ProductDto prod = new ProductDto("苹果","张三","陕西冰糖心");
productChainFactory.execute(prod);
}
可以看到结果:
商品基础校验苹果
商品拥有者校验张三
商品明细信息校验陕西冰糖心
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
2022-10-26 maven 分离打包的技术
2014-10-26 linux 一些命令