一、定义
责任链模式:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递请求,直到有一个对象处理它为止。
二、实现代码
20 //消息处理者的抽象类,主要是由消息处理和设置下一个处理者的方法
21 class Handler
22 {
23 public:
24 virtual void HandlerRequest(std::string iDentifyCard) = 0;
25 virtual void SetNextHandler(Handler * pNext) = 0;
26
27 };
29 class jiangxi : public Handler
30 {
31 public:
32
33 jiangxi()
34 {
35 m_oIDList.push_back(“360321199701065547”);
36 m_oIDList.push_back(“360321199701065590”);
37 m_oIDList.push_back(“360321199703065547”);
38 }
39
40 void HandlerRequest(std::string iDentifyCard)
41 {
42 bool bIsFind = false;
43 std::liststd::string::iterator iIter = m_oIDList.begin();
44
45 for (iIter; iIter != m_oIDList.end(); iIter++)
46 {
47
48 if (*iIter == iDentifyCard)
49 {
50 bIsFind = true;
51 cout << “这个人是江西人” << endl;
52 break;
53 }
54 }
55
56 if (!bIsFind)
57 {
58 if ( m_oNextHandler != NULL )
59 {
60 m_oNextHandler->HandlerRequest(iDentifyCard);
61 }
62 else
63 {
64 cout << “没有找到这个人的信息” << endl;
65 }
66 }
67
68 }
69
70 void SetNextHandler(Handler * pNext)
71 {
72 m_oNextHandler = pNext;
73 }
74
75 private:
76 Handler * m_oNextHandler;
77 std::liststd::string m_oIDList;
78 };
80 class guangdong : public Handler
81 {
82 public:
83
84 guangdong()
85 {
86 m_oIDList.push_back(“360321199701065541”);
87 m_oIDList.push_back(“360321199701065544”);
88 m_oIDList.push_back(“360321199701065542”);
89 }
90
91 void HandlerRequest(std::string iDentifyCard)
92 {
93
94 bool bIsFind = false;
95
96 std::liststd::string::iterator iIter = m_oIDList.begin();
97 for (iIter; iIter != m_oIDList.end(); iIter++)
98 {
99 if (*iIter == iDentifyCard)
100 {
101 bIsFind = true;
102 cout << “这个人是广东人” << endl;
103 break;
104 }
105 }
106
107 if (!bIsFind)
108 {
109 if ( m_oNextHandler != NULL )
110 {
111 m_oNextHandler->HandlerRequest(iDentifyCard);
112 }
113 else
114 {
115 cout << “没有找到这个人的信息, 可能是外星人吧” << endl;
116 }
117 }
118 }
119
120 void SetNextHandler(Handler * pNext)
121 {
122 m_oNextHandler = pNext;
123 }
124
125 private:
126 Handler * m_oNextHandler;
127 std::liststd::string m_oIDList;
128 };
三、测试代码
130 int main()
131 {
132
133 jiangxi * pJX = new jiangxi();
134 guangdong * pGD = new guangdong();
135
136 pJX->SetNextHandler(pGD);
137
138 pJX->HandlerRequest(“360321199701065542”);
139 pJX->HandlerRequest(“360321199701061000”);
140
141 return 0;
142 }
四、运行结果