設計模式 -> 行為型 - 責任鏈(Chain Of Responsibility)
阿新 • • 發佈:2022-05-12
責任鏈模式(Chain of responsibility pattern): 通過責任鏈模式, 你可以為某個請求建立一個物件鏈. 每個物件依序檢查此請求並對其進行處理或者將它傳給鏈中的下一個物件。
1. 意圖
使多個物件都有機會處理請求,從而避免請求的傳送者和接收者之間的耦合關係。將這些物件連成一條鏈,並沿著這條鏈傳送該請求,直到有一個物件處理它為止。
2. 類圖
Handler: 定義處理請求的介面,並且實現後繼鏈(successor)
3. 實現
public abstract class Handler { protected Handler successor; public Handler(Handler successor) { this.successor = successor; } protected abstract void handleRequest(Request request); }
public class ConcreteHandler1 extends Handler { public ConcreteHandler1(Handler successor) { super(successor); } @Override protected void handleRequest(Request request) { if (request.getType() == RequestType.type1) { System.out.println(request.getName() + " is handle by ConcreteHandler1"); return; } if (successor != null) { successor.handleRequest(request); } } }
public class ConcreteHandler2 extends Handler{ public ConcreteHandler2(Handler successor) { super(successor); } @Override protected void handleRequest(Request request) { if (request.getType() == RequestType.type2) { System.out.println(request.getName() + " is handle by ConcreteHandler2"); return; } if (successor != null) { successor.handleRequest(request); } } }
public class Request {
private RequestType type;
private String name;
public Request(RequestType type, String name) {
this.type = type;
this.name = name;
}
public RequestType getType() {
return type;
}
public String getName() {
return name;
}
}
public enum RequestType {
type1, type2
}
public class Client {
public static void main(String[] args) {
Handler handler1 = new ConcreteHandler1(null);
Handler handler2 = new ConcreteHandler2(handler1);
Request request1 = new Request(RequestType.type1, "request1");
handler2.handleRequest(request1);
Request request2 = new Request(RequestType.type2, "request2");
handler2.handleRequest(request2);
}
}