哪种设计模式适配多服务校验的if else逻辑场景?
适配该校验场景的设计模式分析
场景描述
现有三个服务A、B、C,每个服务处理输入后会返回三种输出类型:Invalid(I)、Valid(V)、Unknown(U)。校验规则如下:
- 若任意服务返回Valid或Invalid,则直接返回该结果;
- 若服务返回Unknown,则需继续调用其他支持对应国家的服务;
- 按顺序校验A、B、C,一旦得到Valid或Invalid结果则终止流程,无需调用后续服务。
当前实现代码如下:
output validate(input, country) { response; if A support this country { response = A(input); if response == Invalid or response == Valid { return response; } } if B support this country { if ((response is null) or (response is unknown)){ response = B(input); } if response == Invalid or response == Valid { return response; } } if C support this country { if ((response is null) or (response is unknown)){ response = C(input); } if response == Invalid or response == Valid { return response; } } return response; }
适配的设计模式:责任链模式(Chain of Responsibility Pattern)
适配原因
责任链模式的核心是将请求的发送者与接收者解耦,让多个对象依次有机会处理请求,请求沿链传递直到被处理为止,完全匹配当前场景需求:
- 每个服务A、B、C可封装为链上的独立处理节点;
- 每个节点先判断自身是否支持目标国家,支持则处理请求;
- 若处理结果为Valid或Invalid,直接返回并终止链的传递;
- 若结果为Unknown或节点不支持该国家,则将请求传递给链的下一个节点;
- 所有节点处理完毕后,返回最终结果。
对比当前硬编码的实现,使用责任链模式后,新增/移除服务仅需调整链的节点,无需修改核心校验逻辑,扩展性和维护性更强。
内容的提问来源于stack exchange,提问作者Dilip Agarwal
相关产品推荐
相关产品推荐

