Chinaunix首页 | 论坛 | 博客
  • 博客访问: 170222
  • 博文数量: 60
  • 博客积分: 15
  • 博客等级: 民兵
  • 技术积分: 638
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-26 10:59
个人简介

喜欢coding,因为那是一件伟大的事情,是将无生命的IC赋予灵魂的过程,让我拥有了和上帝一样的成就感。(w1c2g3@163.com)

文章分类

全部博文(60)

文章存档

2017年(7)

2016年(41)

2015年(1)

2014年(4)

2013年(7)

我的朋友

分类: C/C++

2016-10-30 23:13:00

责任链模式 当你想要让一个以上的对象有机会能够处理某个请求的时候,就使用责任链模式。




  1. #include <iostream>

  2. using namespace std;

  3. class Handler {
  4. public:
  5.     Handler(Handler *successor=NULL) {this->successor = successor;}
  6.     virtual ~Handler() {};
  7.     virtual void handleRequest() = 0;
  8. protected:
  9.     Handler *successor;
  10. };

  11. class SpamHandler : public Handler {
  12. public:
  13.     SpamHandler(Handler *successor=NULL) : Handler(successor) {}
  14.     ~SpamHandler() {}
  15.     void handleRequest() {
  16.         cout << "SpamHandler: handleRequest" << endl;
  17.         if (NULL != successor) {
  18.             successor->handleRequest();
  19.         } else {
  20.             cout << "end" <<endl;
  21.         }
  22.     }
  23. };

  24. class FanHandler : public Handler {
  25. public:
  26.     FanHandler(Handler *successor=NULL) : Handler(successor) {}
  27.     ~FanHandler() {}
  28.     void handleRequest() {
  29.         cout << "FanHandler: handleRequest" << endl;
  30.         if (NULL != successor) {
  31.             successor->handleRequest();
  32.         } else {
  33.             cout << "end" <<endl;
  34.         }
  35.     }
  36. };

  37. class ComplaintHandler : public Handler {
  38. public:
  39.     ComplaintHandler(Handler *successor=NULL) : Handler(successor) {}
  40.     ~ComplaintHandler() {}
  41.     void handleRequest() {
  42.         cout << "ComplaintHandler: handleRequest" << endl;
  43.         if (NULL != successor) {
  44.             successor->handleRequest();
  45.         } else {
  46.             cout << "end" <<endl;
  47.         }
  48.     }
  49. };

  50. class NewLocHandler : public Handler {
  51. public:
  52.     NewLocHandler(Handler *successor=NULL) : Handler(successor) {}
  53.     ~NewLocHandler() {}
  54.     void handleRequest() {
  55.         cout << "NewLocHandler: handleRequest" << endl;
  56.         if (NULL != successor) {
  57.             successor->handleRequest();
  58.         } else {
  59.             cout << "end" <<endl;
  60.         }
  61.     }
  62. };


  63. int main(int argc, char **argv) {
  64.     Handler *newLocHandler = new NewLocHandler();
  65.     Handler *complaintHandler = new ComplaintHandler(newLocHandler);
  66.     Handler *fanHandler = new FanHandler(complaintHandler);
  67.     Handler *spamHandler = new SpamHandler(fanHandler);
  68.     Handler *handler = spamHandler;

  69.     handler->handleRequest();
  70. }

阅读(835) | 评论(0) | 转发(0) |
0

上一篇:生成器模式

下一篇:蝇量模式

给主人留下些什么吧!~~