东汉末年,天下三分,魏、蜀、吴三方势力在战略博弈中展现出惊人的组织智慧。诸葛亮"空城计"中层层设防的预警机制,关羽"过五关斩六将"时关卡递进的审查流程,这些历史场景与现代软件设计中的责任链模式(Chain of Responsibility Pattern)存在深刻共鸣。本文将通过分析三国经典战役,解构责任链模式的核心思想,并展示如何用Java实现这种设计模式,最终探讨其在分布式系统中的现代应用。三国演义:责任链模式https://www.sundawu.cn/post-52621.html相关问题,欢迎点击进入网站链接!
public class FirstLineDefense implements GrainDefense {
private GrainDefense next;
@Override
public void defend(int troops) {
if (troops > 30000) {
System.out.println("第一防线:焚毁粮道");
} else if (next != null) {
next.defend(troops);
}
}
// 省略setter方法
}
// 后续防线实现类似结构
这种层级防御机制确保了不同规模的敌军能被对应层级的防御措施拦截,体现了责任链的"各司其职"特性。
2. 赤壁之战的情报传递链
周瑜为实施火攻计划,建立了三级情报网络:
public abstract class IntelligenceChain {
protected IntelligenceChain next;
public void setNext(IntelligenceChain next) {
this.next = next;
}
public abstract void process(String message);
}
public class LocalSpy extends IntelligenceChain {
@Override
public void process(String message) {
if (message.contains("曹军水寨")) {
System.out.println("本地密探:确认水寨位置");
} else if (next != null) {
next.process(message);
}
}
}
情报经过密探→商人→渔民的传递链,最终到达决策层,这种分级处理机制极大提高了信息处理效率。
四、Java实现责任链模式
1. 基础实现框架
以审批流程为例构建责任链:
public abstract class ApprovalHandler {
protected ApprovalHandler nextHandler;
public void setNextHandler(ApprovalHandler next) {
this.nextHandler = next;
}
public abstract void handleRequest(ApprovalRequest request);
}
public class DepartmentHead extends ApprovalHandler {
@Override
public void handleRequest(ApprovalRequest request) {
if (request.getAmount()
2. 完整审批链示例
public class ApprovalChainDemo {
public static void main(String[] args) {
ApprovalHandler deptHead = new DepartmentHead();
ApprovalHandler vp = new VicePresident();
ApprovalHandler ceo = new CEO();
public class HandlerFactory {
public static ApprovalHandler createChain() {
ApprovalHandler dept = new DepartmentHead();
ApprovalHandler vp = new VicePresident();
ApprovalHandler ceo = new CEO();
public abstract class ZuulFilter {
private ZuulFilter next;
public abstract int filterOrder();
public abstract boolean shouldFilter();
public abstract Object run() throws ZuulException;
public Object process(RequestContext ctx) {
if (shouldFilter()) {
return run();
}
if (next != null) {
return next.process(ctx);
}
return null;
}
}
2. 消息中间件处理