初学设计模式之责任链模式

责任链模式的代码例子

  1 #include <iostream>
  2 #include<string>
  3 using namespace std;
  4 class Thing
  5 {
  6 private:
  7     int type;
  8     string require;
  9 public:
 10     Thing(string str,int m_type)
 11     {   
 12         require=str;
 13         type=m_type;
 14     };
 15     int getType()
 16     {
 17         return type;
 18     };
 19     string getRequire()
 20     {
 21         return require;
 22     }
 23 };
 24 
 25 class Handler
 26 {
 27 protected:
 28     int level;
 29     Handler *m_Nexthandler;
 30 public:
 31     Handler(int level,Handler* ptr):level(level),m_Nexthandler(ptr){};
 32     void setNextHandler(Handler *handler)
 33     {
 34         m_Nexthandler=handler;
 35     }
 36     void handleMessage(Thing m_thing)
 37     {
 38         if (m_thing.getType()==level)
 39         {
 40             responce(m_thing);
 41         }
 42         else
 43         {
 44             if (m_Nexthandler!=NULL)
 45             {
 46                 m_Nexthandler->handleMessage(m_thing);
 47             }
 48             else
 49             {
 50                 cout<<"无人能处理"<<endl;
 51             }
 52         }
 53 
 54     }
 55     virtual void responce(Thing m_thing){};
 56 };
 57 class High:public Handler
 58 {
 59 public:
 60     High(int level,Handler* ptr):Handler(level,ptr){};
 61     void responce(Thing m_thing)
 62     {
 63     cout<<"高层对于"<<m_thing.getRequire()<<"的回复"<<endl;
 64     };
 65 
 66 };
 67 
 68 class Med:public Handler
 69 {
 70 public:
 71     Med(int level,Handler* ptr):Handler(level,ptr){};
 72     void responce(Thing m_thing)
 73     {
 74     cout<<"中层对于"<<m_thing.getRequire()<<"的回复"<<endl;
 75     };
 76 
 77 };
 78 
 79 class Low:public Handler
 80 {
 81     public:
 82         Low(int level,Handler* ptr):Handler(level,ptr){};
 83     void responce(Thing m_thing)
 84     {
 85     cout<<"基层对于"<<m_thing.getRequire()<<"的回复"<<endl;
 86     };
 87 
 88 };
 89 
 90 int main()
 91 {
 92     Thing thing("一个请求",2);//可以更改请求级别,来获取不同级别的处理
 93     High *m_high=new High(3,NULL);
 94     Med *m_med=new Med(2,NULL);
 95     Low *m_low=new Low(1,NULL);
 96 
 97     m_low->setNextHandler(m_med);
 98     m_med->setNextHandler(m_high);
 99     m_low->handleMessage(thing);
100     
101     getchar();
102 return 0;
103 };

猜你喜欢

转载自www.cnblogs.com/wuhongjian/p/11816967.html