Java中實現責任鏈模式可以使用以下步驟:
public abstract class Handler {
protected Handler nextHandler;
public void setNextHandler(Handler nextHandler) {
this.nextHandler = nextHandler;
}
public abstract void handleRequest(Request request);
}
public class ConcreteHandlerA extends Handler {
@Override
public void handleRequest(Request request) {
if (request.getType() == RequestType.TYPE_A) {
// 處理請求的邏輯
System.out.println("ConcreteHandlerA handles request: " + request);
} else if (nextHandler != null) {
// 將請求傳遞給下一個處理器
nextHandler.handleRequest(request);
}
}
}
public class ConcreteHandlerB extends Handler {
@Override
public void handleRequest(Request request) {
if (request.getType() == RequestType.TYPE_B) {
// 處理請求的邏輯
System.out.println("ConcreteHandlerB handles request: " + request);
} else if (nextHandler != null) {
// 將請求傳遞給下一個處理器
nextHandler.handleRequest(request);
}
}
}
// 其他具體處理器類的定義...
public class Request {
private RequestType type;
private String data;
public Request(RequestType type, String data) {
this.type = type;
this.data = data;
}
public RequestType getType() {
return type;
}
public String getData() {
return data;
}
@Override
public String toString() {
return "Request [type=" + type + ", data=" + data + "]";
}
}
public class Client {
public static void main(String[] args) {
// 創建具體處理器的實例
Handler handlerA = new ConcreteHandlerA();
Handler handlerB = new ConcreteHandlerB();
// 設置處理器之間的關系
handlerA.setNextHandler(handlerB);
// 創建請求
Request requestA = new Request(RequestType.TYPE_A, "Request A");
Request requestB = new Request(RequestType.TYPE_B, "Request B");
// 處理請求
handlerA.handleRequest(requestA); // ConcreteHandlerA handles request: Request [type=TYPE_A, data=Request A]
handlerA.handleRequest(requestB); // ConcreteHandlerB handles request: Request [type=TYPE_B, data=Request B]
}
}
注意:責任鏈模式的關鍵在于設置處理器之間的關系,確保每個處理器都有下一個處理器的引用。處理器按照順序依次處理請求,如果某個處理器能夠處理該請求,則進行處理;否則將請求傳遞給下一個處理器。