Java Chain of Responsibility Pattern Guide
The implementation method of the chain of responsibility pattern in Java is as follows:
- Define an abstract Handler class that contains an abstract method for processing requests and defines a reference to the next handler. This class can be implemented as an interface or abstract class.
- Define a specific processor (ConcreteHandler) class that extends or implements the abstract processor class and implements its handling method. In the handling method, check if it can handle the request, if so, process it, otherwise pass the request to the next handler.
- In the client-side code, a handler chain is created to pass requests to each handler in the chain for processing.
Here is an example:
// 抽象处理器类
abstract class Handler {
protected Handler nextHandler;
public void setNextHandler(Handler nextHandler) {
this.nextHandler = nextHandler;
}
public abstract void handleRequest(String request);
}
// 具体处理器类1
class ConcreteHandler1 extends Handler {
@Override
public void handleRequest(String request) {
if (request.equals("request1")) {
System.out.println("ConcreteHandler1 handles request1");
} else if (nextHandler != null) {
nextHandler.handleRequest(request);
}
}
}
// 具体处理器类2
class ConcreteHandler2 extends Handler {
@Override
public void handleRequest(String request) {
if (request.equals("request2")) {
System.out.println("ConcreteHandler2 handles request2");
} else if (nextHandler != null) {
nextHandler.handleRequest(request);
}
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
Handler handler1 = new ConcreteHandler1();
Handler handler2 = new ConcreteHandler2();
handler1.setNextHandler(handler2);
handler1.handleRequest("request1");
handler1.handleRequest("request2");
handler1.handleRequest("request3");
}
}
The output result is:
ConcreteHandler1 handles request1
ConcreteHandler2 handles request2
In the example above, the abstract handler class defines an abstract method handleRequest. The concrete handler class inherits from the abstract handler class and implements this method. In the client code, a handler chain is created to pass the request to each handler for processing. If a handler can process the request, it does so; if not, the request is passed to the next handler.