职责链模式是一种行为设计模式,它允许你将请求沿着处理者链进行传递,直到其中一个处理者能够处理该请求为止。
// 抽象处理者
public abstract class Handler {
protected Handler successor;
public void setSuccessor(Handler successor) {
this.successor = successor;
}
public abstract void handleRequest(Request request);
}
// 具体处理者1
public class ConcreteHandler1 extends Handler {
public void handleRequest(Request request) {
if (request.getType() == RequestType.TYPE1) {
System.out.println("ConcreteHandler1 handles the request.");
} else if (successor != null) {
successor.handleRequest(request);
}
}
}
// 具体处理者2
public class ConcreteHandler2 extends Handler {
public void handleRequest(Request request) {
if (request.getType() == RequestType.TYPE2) {
System.out.println("ConcreteHandler2 handles the request.");
} else if (successor != null) {
successor.handleRequest(request);
}
}
}
// 请求类
public class Request {
private final RequestType type;
public Request(RequestType type) {
this.type = type;
}
public RequestType getType() {
return type;
}
}
// 请求类型枚举
public enum RequestType {
TYPE1, TYPE2
}
public class Client {
public static void main(String[] args) {
// Setup the chain of handlers
Handler handler1 = new ConcreteHandler1();
Handler handler2 = new ConcreteHandler2();
Handler handler3 = new ConcreteHandler3();
handler1.setSuccessor(handler2);
handler2.setSuccessor(handler3);
// Send requests to the first handler
handler1.handleRequest(new Request("Type1"));
handler1.handleRequest(new Request("Type2"));
handler1.handleRequest(new Request("Type3"));
}
}
涉及到的角色
角色 | 作用 |
---|---|
Handler | 定义处理请求的接口和知道“下一个处理者” |
ConcreteHandler | 具体的处理者 |
Client | 请求者 |