責任鏈模式
責任鏈模式(Chain of Responsibility Pattern)是一種行為型設計模式,它將請求的傳送者和接收者解耦,使多個物件都有機會處理這個請求。每個接收者都包含對下一個接收者的引用,形成一個鏈條,請求沿著這個鏈條依次傳遞,直到有一個接收者處理它。
下面是一個簡單的Java程式碼示例,演示了責任鏈模式的實現:
// 請求類
class Request {
private String content;
public Request(String content) {
this.content = content;
}
public String getContent() {
return content;
}
}
// 處理者介面
interface Handler {
void setNext(Handler nextHandler);
void handleRequest(Request request);
}
// 具體處理者A
class ConcreteHandlerA implements Handler {
private Handler nextHandler;
public void setNext(Handler nextHandler) {
this.nextHandler = nextHandler;
}
public void handleRequest(Request request) {
if (request.getContent().equals("A")) {
System.out.println("ConcreteHandlerA handles the request.");
} else if (nextHandler != null) {
nextHandler.handleRequest(request);
}
}
}
// 具體處理者B
class ConcreteHandlerB implements Handler {
private Handler nextHandler;
public void setNext(Handler nextHandler) {
this.nextHandler = nextHandler;
}
public void handleRequest(Request request) {
if (request.getContent().equals("B")) {
System.out.println("ConcreteHandlerB handles the request.");
} else if (nextHandler != null) {
nextHandler.handleRequest(request);
}
}
}
// 客戶端程式碼
public class ChainOfResponsibilityPatternExample {
public static void main(String[] args) {
Handler handlerA = new ConcreteHandlerA();
Handler handlerB = new ConcreteHandlerB();
handlerA.setNext(handlerB);
Request request1 = new Request("A");
handlerA.handleRequest(request1);
Request request2 = new Request("B");
handlerA.handleRequest(request2);
Request request3 = new Request("C");
handlerA.handleRequest(request3);
}
}