责任链模式是一种行为设计模式,它允许多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合。这些对象被连成一条链,并沿着这条链传递请求,直到有一个对象处理它为止。
定义处理器抽象类
java
public abstract class Handler {
protected Handler nextHandler;
public void setNextHandler(Handler nextHandler) {
this.nextHandler = nextHandler;
}
public void handleRequest(String request) {
if (nextHandler != null) {
nextHandler.handleRequest(request);
}
}
}
实现具体处理器
java
public class ConcreteHandlerA extends Handler {
@Override
public void handleRequest(String request) {
if (request.equals("A")) {
System.out.println("ConcreteHandlerA handled request: " + request);
} else {
super.handleRequest(request);
}
}
}
public class ConcreteHandlerB extends Handler {
@Override
public void handleRequest(String request) {
if (request.equals("B")) {
System.out.println("ConcreteHandlerB handled request: " + request);
} else {
super.handleRequest(request);
}
}
}
public class ConcreteHandlerC extends Handler {
@Override
public void handleRequest(String request) {
if (request.equals("C")) {
System.out.println("ConcreteHandlerC handled request: " + request);
} else {
super.handleRequest(request);
}
}
}
使用责任链模式
java
public class ChainOfResponsibilityPatternDemo {
public static void main(String[] args) {
// 创建处理器
Handler handlerA = new ConcreteHandlerA();
Handler handlerB = new ConcreteHandlerB();
Handler handlerC = new ConcreteHandlerC();
// 设置责任链
handlerA.setNextHandler(handlerB);
handlerB.setNextHandler(handlerC);
// 处理请求
handlerA.handleRequest("A");
handlerA.handleRequest("B");
handlerA.handleRequest("C");
handlerA.handleRequest("D");
}
}