java 实现责任链设计模式
时间: 2023-10-18 12:12:57 浏览: 103
责任链设计模式是一种行为设计模式,它通过一系列对象来处理请求,并将请求沿着对象链传递,直到有一个对象能够处理请求为止。以下是 Java 实现责任链设计模式的示例:
首先,需要定义一个处理请求的接口,例如:
```java
public interface Handler {
void setNextHandler(Handler nextHandler);
void handleRequest(Request request);
}
```
然后,实现具体的处理者类,例如:
```java
public class ConcreteHandler1 implements Handler {
private Handler nextHandler;
@Override
public void setNextHandler(Handler nextHandler) {
this.nextHandler = nextHandler;
}
@Override
public void handleRequest(Request request) {
if (request.getType() == RequestType.TYPE1) {
System.out.println("ConcreteHandler1 handles request " + request);
} else if (nextHandler != null) {
nextHandler.handleRequest(request);
}
}
}
public class ConcreteHandler2 implements Handler {
private Handler nextHandler;
@Override
public void setNextHandler(Handler nextHandler) {
this.nextHandler = nextHandler;
}
@Override
public void handleRequest(Request request) {
if (request.getType() == RequestType.TYPE2) {
System.out.println("ConcreteHandler2 handles request " + request);
} else if (nextHandler != null) {
nextHandler.handleRequest(request);
}
}
}
//...其他具体的处理者类
```
最后,定义一个请求类:
```java
public class Request {
private RequestType type;
private String content;
public Request(RequestType type, String content) {
this.type = type;
this.content = content;
}
public RequestType getType() {
return type;
}
public String getContent() {
return content;
}
@Override
public String toString() {
return "[" + type + ", " + content + "]";
}
}
```
在客户端中,可以创建一个处理者链,并将请求传递给处理者链的第一个处理者:
```java
public class Client {
public static void main(String[] args) {
Handler handler1 = new ConcreteHandler1();
Handler handler2 = new ConcreteHandler2();
//...其他具体的处理者
//设置处理者链
handler1.setNextHandler(handler2);
//...设置其他处理者的下一个处理者
//创建请求
Request request1 = new Request(RequestType.TYPE1, "Request 1");
Request request2 = new Request(RequestType.TYPE2, "Request 2");
//...其他请求
//传递请求
handler1.handleRequest(request1);
handler1.handleRequest(request2);
//...处理其他请求
}
}
```
输出结果:
```
ConcreteHandler1 handles request [TYPE1, Request 1]
ConcreteHandler2 handles request [TYPE2, Request 2]
```
阅读全文