改进型责任链(处理器链)

本文介绍了一种使用Java实现的责任链模式案例。通过定义一个抽象处理器`AbstractMatchHandler`及其实现类`BankSerialNoMatchHandler`和`PayElementMatchHandler`,展示了如何处理支付匹配流程。同时,还提供了一个`MatchHandlerChain`类来管理处理器链,从而实现请求的灵活处理。

1 抽象处理器

public abstract class AbstractMatchHandler {

    private AbstractMatchHandler nextHandler;

    protected AbstractMatchHandler getNextHandler() {
        return nextHandler;
    }

    public void setNextHandler(AbstractMatchHandler nextHandler) {
        this.nextHandler = nextHandler;
    }

    abstract public void doHandle(CSCPolling cscPolling, MatchHandlerChain matchHandlerChain) throws Exception;
}

2 实现具体处理器(两个)

public class BankSerialNoMatchHandler extends AbstractMatchHandler {

    @Override
    public void doHandle(CSCPolling cscPolling, MatchHandlerChain matchHandlerChain) throws Exception{

        
      if(满足本处理器处理的条件){
	    // 从matchHandlerChain.xxx中获取链全局参数,修改链结果
}else {
            // 交互链上下一级处理器
            getNextHandler().doHandle(cscPolling,matchHandlerChain);
        }
    }
}


public class PayElementMatchHandler extends AbstractMatchHandler {

    @Override
    public void doHandle(CSCPolling cscPolling, MatchHandlerChain matchHandlerChain) throws Exception {

        if(满足本处理器条件){		
	   // 从matchHandlerChain.xxx中获取链全局参数,修改链结果
	}
    }
}

3 链管理器

public class MatchHandlerChain {

    private List<CSCPolling> result = new ArrayList<>();// 结果

    private AbstractMatchHandler headerHander;// 链头handler

    List<CSCPolling> pollings;// 待处理数据
    Map<String,CSCDto> params;// 参数

    public MatchHandlerChain()throws NoSuchAlgorithmException{
        // 构造器
    }

    public void doHandle() throws Exception{
        for(CSCPolling cscPolling : pollings){
            headerHander.doHandle(cscPolling, this);
        }
    }

    public List<CSCPolling> getResult() {
        return result;
    }
}

4 执行
AbstractMatchHandler bankSerialNoMatchHandler = new BankSerialNoMatchHandler();
AbstractMatchHandler payElementMatchHandler = new PayElementMatchHandler();
bankSerialNoMatchHandler.setNextHandler(payElementMatchHandler);//指定链上处理器前后关系
MatchHandlerChain matchHandlerChain = new MatchHandlerChain(pollings,params,bankSerialNoMatchHandler);
matchHandlerChain.doHandle();
List<CSCPolling> result= matchHandlerChain.getResult();




评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值