#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// 定义业务处理者抽象类
typedef struct Handler {
struct Handler* nextHandler;
void (*handleRequest)(struct Handler* handler, int request);
void (*setNextHandler)(struct Handler* CurHandler, struct Handler* NextHandler);
} Handler;
void setNextHandler(struct Handler* CurHandler, struct Handler* NextHandler)
{
if (!CurHandler) {
printf("handler is null\n");
return;
}
CurHandler->nextHandler = NextHandler;
}
// 业务处理者子类1
typedef struct ConcreteHandler1 {
Handler handler;
} ConcreteHandler1;
void ConcreteHandler1_handleRequest(Handler* handler, int request) {
if (request >= 0 && request < 10) {
printf("ConcreteHandler1 处理请求 %d\n", request);
} else if (handler->nextHandler != NULL) {
// 转发给下一个处理者
handler->nextHandler->handleRequest(handler->nextHandler, request);
} else {
printf("无法处理请求 %d\n", request);
}
}
// 业务处理者子类2
typedef struct ConcreteHandler2 {
Handler handler;
} ConcreteHandler2;
void ConcreteHandler2_handleRequest(Handler* handler, int request) {
if (request >= 10 && request < 20) {
printf("ConcreteHandler2 处理请求 %d\n", request);
} else if (handler->nextHandler != NULL) {
// 转发给下一个处理者
handler->nextHandler->handleRequest(handler->nextHandler, request);
} else {
printf("无法处理请求 %d\n", request);
}
}
int main(int argc, char *argv[])
{
// 创建业务处理者对象
ConcreteHandler1* handler1 = (ConcreteHandler1*)malloc(sizeof(ConcreteHandler1));
ConcreteHandler2* handler2 = (ConcreteHandler2*)malloc(sizeof(ConcreteHandler2));
// 设置责任链关系
handler1->handler.handleRequest = ConcreteHandler1_handleRequest;
handler1->handler.setNextHandler = setNextHandler;
handler1->handler.setNextHandler(&handler1->handler, &handler2->handler);
handler2->handler.handleRequest = ConcreteHandler2_handleRequest;
handler1->handler.setNextHandler = setNextHandler;
handler1->handler.setNextHandler(&handler2->handler, NULL);
// 模拟客户端发送请求
int requests[] = {5, 12, 18, 25};
int i;
for (i = 0; i < sizeof(requests) / sizeof(int); i++) {
handler1->handler.handleRequest((Handler*)handler1, requests[i]);
}
// 释放内存
free(handler1);
free(handler2);
return 0;
}
- ()[https://zhuanlan.zhihu.com/p/670001095]
- ()[https://blog.csdn.net/feixiaoxing/article/details/7085567]
- ()[https://blog.csdn.net/jenie/article/details/106484892]