介绍:
责任链模式
是一种行为模式,它可以允许你将请求沿着处理者链进行发送,收到请求以后, 每个处理者均可对请求进行处理, 或将其传递给链上的下个处理者;
作用:
将请求按照链的方式一一传递
类比:
公司申请报销,首先要leader审批通过,然后是HR,再然后是财务,最后是老板,一级一级的将请求传递;
示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
#include <stdio.h> #include <assert.h> #include "list.h" static LIST_HEAD(chain_head); enum { PASS, REFUSE, }; typedef struct { int money; char * files; } info_t; typedef int (*request_handle)(info_t* info); typedef struct { request_handle func; ListObj list; }chain_node_t; int leader(info_t* info) { assert (info != NULL); if (info->money < 1000) //金额小于1000就行 { return PASS; } return REFUSE; } int hr(info_t* info) { assert (info != NULL); if (info->money < 2000 && info->files != NULL) //金额小于2000且材料齐全 { return PASS; } return REFUSE; } int boss(info_t* info) { assert (info != NULL); if (info->files != NULL) //材料齐全就行,不差钱 { return PASS; } return REFUSE; } //审批流程: leader->hr->boss chain_node_t req_table[] = { {.func = leader}, {.func = hr}, {.func = boss} }; void main( void ) { /*将审批节点添加到责任链上*/ for ( int i = 0; i < sizeof (req_table) / sizeof (req_table[0]); i++) { list_insert_before(&chain_head, &(req_table[i].list)); } /*报销内容*/ info_t info = {.money = 900, .files = "files" }; ListObj *node; list_for_each(node, &chain_head) { chain_node_t* req = list_entry(node, chain_node_t, list); if (req->func(&info) != PASS) { /*报销失败*/ printf ( "Failed\r\n" ); return ; } } /*报销成功*/ printf ( "Success\r\n" ); return ; } |
总结
到此这篇关于C语言责任链模式示例代码的文章就介绍到这了,更多相关C语言责任链内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/weixin_41917404/article/details/122320787