📅  最后修改于: 2023-12-03 15:12:13.328000             🧑  作者: Mango
责任链模式是一种行为型设计模式,它允许多个对象都有机会处理请求,从而避免了请求发送者和接收者之间的耦合关系。在该模式中,请求沿着处理链一直传递,直到有一个对象处理了该请求。
责任链模式的结构包含以下几个部分:
下图展示了责任链模式的结构:
下面以一个简单的实例来说明责任链模式的使用方法:
假设现在有三个处理者,每个处理者可以处理一定范围内的请求。当一个请求被发送时,如果第一个处理者无法处理该请求,则将其传递给下一个处理者,直到有一个处理者处理了该请求。请求的类型和处理范围如下表所示:
| 请求类型 | 处理范围 | | -------- | ------------------------ | | 1 | 0 ~ 10 | | 2 | 10 ~ 20 | | 3 | 20 ~ 30 | | 4 | 30 ~ 40 | | 5 | 大于等于40 |
下面是实现代码:
// Handler.java
public interface Handler {
void handleRequest(Request request);
void setNextHandler(Handler handler);
}
// ConcreteHandler1.java
public class ConcreteHandler1 implements Handler {
private Handler nextHandler;
@Override
public void handleRequest(Request request) {
if(request.getType() >= 0 && request.getType() <= 10) {
System.out.println("ConcreteHandler1 处理了请求:" + request.getDescription());
}else {
nextHandler.handleRequest(request);
}
}
@Override
public void setNextHandler(Handler handler) {
this.nextHandler = handler;
}
}
// ConcreteHandler2.java
public class ConcreteHandler2 implements Handler {
private Handler nextHandler;
@Override
public void handleRequest(Request request) {
if(request.getType() > 10 && request.getType() <= 20) {
System.out.println("ConcreteHandler2 处理了请求:" + request.getDescription());
}else {
nextHandler.handleRequest(request);
}
}
@Override
public void setNextHandler(Handler handler) {
this.nextHandler = handler;
}
}
// ConcreteHandler3.java
public class ConcreteHandler3 implements Handler {
private Handler nextHandler;
@Override
public void handleRequest(Request request) {
if(request.getType() > 20 && request.getType() <= 30) {
System.out.println("ConcreteHandler3 处理了请求:" + request.getDescription());
}else {
nextHandler.handleRequest(request);
}
}
@Override
public void setNextHandler(Handler handler) {
this.nextHandler = handler;
}
}
// Request.java
public class Request {
private int type;
private String description;
public Request(int type, String description) {
this.type = type;
this.description = description;
}
public int getType() {
return type;
}
public String getDescription() {
return description;
}
}
// Client.java
public class Client {
public static void main(String[] args) {
Handler h1 = new ConcreteHandler1();
Handler h2 = new ConcreteHandler2();
Handler h3 = new ConcreteHandler3();
h1.setNextHandler(h2);
h2.setNextHandler(h3);
Request r1 = new Request(1, "我是请求1");
Request r2 = new Request(10, "我是请求10");
Request r3 = new Request(20, "我是请求20");
Request r4 = new Request(30, "我是请求30");
Request r5 = new Request(50, "我是请求50");
h1.handleRequest(r1);
h1.handleRequest(r2);
h1.handleRequest(r3);
h1.handleRequest(r4);
h1.handleRequest(r5);
}
}