c++之职责链模式
发布日期:2021-09-25 21:40:59 浏览次数:2 分类:技术文章

本文共 1221 字,大约阅读时间需要 4 分钟。

职责链模式

定义:使得多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系,将这个对象连成一条链,并沿着该链传递该请求,直到有一个对象处理它为止。

属于行为型模式。

代码:

#include 
using namespace std;class Handle{public: void setHandle(Handle *h) { m_handle = h; } virtual void handleRequest(int score) = 0; Handle *m_handle;};class ConcreteHandleA :public Handle{public: void handleRequest(int score) { if (score < 60) { cout << score << " 不及格,调入普通班级" << endl; } else { if (m_handle) m_handle->handleRequest(score); } }};class ConcreteHandleB :public Handle{public: void handleRequest(int score) { if (score >= 60 && score<80) { cout << score << " 及格,调入良好班级" << endl; } else { if (m_handle) m_handle->handleRequest(score); } }};class ConcreteHandleC :public Handle{public: void handleRequest(int score) { if (score >= 90) { cout << score << " 优秀,调入尖子班" << endl; } }};//客户端int main(){ ConcreteHandleA *a = new ConcreteHandleA; ConcreteHandleB *b = new ConcreteHandleB; ConcreteHandleC *c = new ConcreteHandleC; a->setHandle(b); b->setHandle(c); int stuScore[] = { 30, 10, 80, 90, 99, 75, 49 }; for (int x : stuScore) { a->handleRequest(x); } if (a) { delete a; a = nullptr; } if (b) { delete b; b = nullptr; } if (c) { delete c; c = nullptr; }}

效果:

转载地址:https://blog.csdn.net/c_shell_python/article/details/107563945 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:c++深拷贝与浅拷贝
下一篇:c++之中介者模式

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2024年04月08日 10时37分11秒