首页 > 解决方案 > 责任链模式是否可以很好地替代一系列条件?

问题描述

当您需要以特定顺序执行一系列操作时,责任链模式是否可以很好地替代一系列条件?用这样的条件替换一个简单的方法是个好主意:

public class MyListener implements MyHttpListener {

    // if false, the request will be thrown away and subsequent listeners will not be notified
    @Override
    public boolean onHttpRequestSend(HttpMessage msg) { 
        // handlers can change msg

        boolean isA = handleA(msg);
        if (isA) return false;

        boolean isB_notA = handleB(msg);
        if (isB_notA) return false;

        boolean isC_notA_notB = handleC(msg);
        if (isC_notA_notB) return true;

        ...

        throw new IllegalStateException();
    }
}

现在将其替换为责任链模式的实现:

public class MyListener implements MyHttpListener {
    @Override
    public boolean onHttpRequestSend(HttpMessage msg) {
        ProcessingStep first = new StepA()
        ProcessingResult result = first.process(new ProcessingResult(msg, true));
        return result.returnValue;
    }
}

public interface ProcessingStep {
    ProcessingResult process(ProcessingResult stepResult);
}

public class ProcessingResult {
    HttpMessage message;
    boolean returnValue;
}

public class StepA implements ProcessingStep {
    @Override
    public ProcessingResult process(ProcessingResult stepResult) {
        if (handleA()) {
            return stepResult;
        }
        else {
            return new StepB().process(stepResult);
        }
    }
}   
public class StepB implements ProcessingStep {
    @Override
    public ProcessingResult process(ProcessingResult stepResult) {
        return stepResult; // this is the last step
    }
}

标签: javaoopdesign-patternschain-of-responsibility

解决方案


对责任链模式的实现并不是一个精确的实现,因为通常处理程序链的每个元素都必须不知道接下来会发生什么。

然而,让我们看看 CoR 模式的主要好处:它能够在运行时动态更改处理程序链(这在硬编码的一系列条件下可能不可用)。所以,如果你需要 CoR 模式的动态行为,你可以从中受益,但如果不需要,它可以被认为是一个不必要的过度设计的解决方案。


推荐阅读