责任链设计模式c++
时间: 2023-11-08 10:01:47 浏览: 52
责任链设计模式是一种行为设计模式,它允许你将请求沿着处理者链进行传递,直到有一个处理者能够处理该请求。每个处理者都可以决定是否要处理该请求,或者将其传递给链中的下一个处理者。
在责任链设计模式中,有以下几个角色:
1. 抽象处理者(Handler):定义了处理请求的接口,并维护了对下一个处理者的引用。
2. 具体处理者(ConcreteHandler):实现了抽象处理者的接口,处理它所负责的请求,如果不能处理则将请求传递给下一个处理者。
责任链设计模式通常用于以下场景:
- 当有多个对象可以处理同一个请求,但具体由哪个对象处理该请求在运行时才能确定。
- 当不希望请求的发送者和接收者之间耦合在一起,使得发送者不需要知道请求的处理者是谁。
代码示例:
```java
// 抽象处理者
abstract class Handler {
private Handler nextHandler;
public void setNextHandler(Handler nextHandler) {
this.nextHandler = nextHandler;
}
public void handleRequest(Request request) {
if (canHandle(request)) {
// 处理请求
System.out.println("处理请求:" + request);
} else if (nextHandler != null) {
// 传递给下一个处理者
nextHandler.handleRequest(request);
} else {
// 没有处理者能够处理该请求
System.out.println("无法处理请求:" + request);
}
}
// 判断是否能够处理该请求的抽象方法
protected abstract boolean canHandle(Request request);
}
// 具体处理者A
class ConcreteHandlerA extends Handler {
@Override
protected boolean canHandle(Request request) {
// 判断是否能够处理该请求
return request.getType() == RequestType.TYPE_A;
}
}
// 具体处理者B
class ConcreteHandlerB extends Handler {
@Override
protected boolean canHandle(Request request) {
// 判断是否能够处理该请求
return request.getType() == RequestType.TYPE_B;
}
}
// 请求类
class Request {
private RequestType type;
public Request(RequestType type) {
this.type = type;
}
public RequestType getType() {
return type;
}
}
// 请求类型枚举
enum RequestType {
TYPE_A, TYPE_B
}
```