java - 责任链模式是否可以很好地替代一系列条件?
问题描述
当您需要以特定顺序执行一系列操作时,责任链模式是否可以很好地替代一系列条件?用这样的条件替换一个简单的方法是个好主意:
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
}
}
解决方案
您对责任链模式的实现并不是一个精确的实现,因为通常处理程序链的每个元素都必须不知道接下来会发生什么。
然而,让我们看看 CoR 模式的主要好处:它能够在运行时动态更改处理程序链(这在硬编码的一系列条件下可能不可用)。所以,如果你需要 CoR 模式的动态行为,你可以从中受益,但如果不需要,它可以被认为是一个不必要的过度设计的解决方案。
推荐阅读
- c# - 如何在 C# 中使用 Microsoft.Azure.Management.Automation AutomationClient 启动 Azure Runbook/webhook?
- c++ - 错误:未在此范围内声明“sumProduct”
- ios - yarn run ios - 错误:找不到模块 - React Native
- powershell-4.0 - 在powershell中创建一个环回,直到满足变量
- dc.js - 如何在我的交叉过滤器组中使用自定义减少功能?
- excel - VBA Excel 查找 2 个动态范围之间的值
- javascript - 通过 socket.io 发送 var
- c# - 使用双精度列表中的 foreach 循环创建字符串列表。每两个值必须压缩成一个字符串,然后添加到列表中
- c++ - 标头中的 inline 和 constexpr 无捕获 lambda 有什么区别?
- php - PHP Soap 客户端请求使用单个字符串回答