The Chain of Responsibility pattern is a behavioral design pattern that lets multiple objects have a chance to handle a request, avoiding coupling the sender of the request to its receiver. These objects are chained together and pass the request along the chain until an object handles it.
定义处理器抽象类
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");
}
}