java 职责链模式 例子
时间: 2023-05-18 11:06:18 浏览: 134
职责链模式是一种行为设计模式,它允许你将请求沿着处理者链进行发送,直到其中一个处理者对其进行处理为止。下面是一个 Java 职责链模式的例子:
```java
public abstract class Handler {
protected Handler successor;
public void setSuccessor(Handler successor) {
this.successor = successor;
}
public abstract void handleRequest(Request request);
}
public class ConcreteHandler1 extends Handler {
public void handleRequest(Request request) {
if (request.getType() == RequestType.TYPE1) {
System.out.println("ConcreteHandler1 handles request " + request);
} else if (successor != null) {
successor.handleRequest(request);
}
}
}
public class ConcreteHandler2 extends Handler {
public void handleRequest(Request request) {
if (request.getType() == RequestType.TYPE2) {
System.out.println("ConcreteHandler2 handles request " + request);
} else if (successor != null) {
successor.handleRequest(request);
}
}
}
public class Request {
private final RequestType type;
private final String description;
public Request(RequestType type, String description) {
this.type = type;
this.description = description;
}
public RequestType getType() {
return type;
}
public String getDescription() {
return description;
}
public String toString() {
return description;
}
}
public enum RequestType {
TYPE1, TYPE2
}
public class Client {
public static void main(String[] args) {
Handler h1 = new ConcreteHandler1();
Handler h2 = new ConcreteHandler2();
h1.setSuccessor(h2);
// Generate and process request
Request req1 = new Request(RequestType.TYPE1, "Request 1");
h1.handleRequest(req1);
Request req2 = new Request(RequestType.TYPE2, "Request 2");
h1.handleRequest(req2);
}
}
```
在这个例子中,我们定义了一个抽象的处理者类 Handler,它有一个指向下一个处理者的引用 successor,以及一个抽象的处理请求的方法 handleRequest。然后我们定义了两个具体的处理者类 ConcreteHandler1 和 ConcreteHandler2,它们分别处理 RequestType.TYPE1 和 RequestType.TYPE2 类型的请求。最后,我们定义了一个 Request 类来表示请求,以及一个 RequestType 枚举来表示请求的类型。在客户端代码中,我们创建了一个处理者链,将请求沿着链进行传递,直到其中一个处理者对其进行处理为止。
阅读全文