design pattern CHAIN of reponsibility 发表于 2010-05-24 | 更新于: 2017-10-12 | | 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980#include<cstdio>using namespace std;namespace pattern{ /// this pattern links all handler as a line, if previous handler can process a request, it wil not be /// send to next handler. For example, if someone requested changing programming style, /// this decision will be made by a programmer. /// He will change his programming style without noticing his lead. /// But if someone request changing the requirements, the programmer can not make this decision. /// He will noticing his lead, and make his lead decided. /// this is request class. #define STYLE 0 #define REQIREMENT 1 class Request{ public: int type; // changing programming style or changing requirements? }; /// this class for processing request. class Handler{ private: Handler* parent; public: Handler(Handler* p):parent(p){} virtual bool DoHandle(Request& r)=0; void Process(Request& r); virtual ~Handler(){} }; void Handler::Process(Request& r){ if(!this->DoHandle(r) && NULL != parent){ parent->Process(r); } } class Programmer: public Handler{ public: Programmer(Handler* p):Handler(p){} virtual bool DoHandle(Request& r); }; bool Programmer::DoHandle(Request& r){ if(r.type == STYLE){ printf("programmer: I can process changing programming style\n"); return true; }else{ printf("programmer: I can not process this request. I will report this to my lead!\n"); return false; } } class Lead:public Handler{ public: Lead(Handler* p):Handler(p){} virtual bool DoHandle(Request& r); }; bool Lead::DoHandle(Request& r){ if(r.type == REQIREMENT){ printf("lead: I will process changing reqirements\n"); return true; } return false; }}int main(){ pattern::Lead lead((pattern::Handler*)NULL); pattern::Programmer programmer(&lead); pattern::Request r; r.type = STYLE; programmer.Process(r); r.type = REQIREMENT; programmer.Process(r); return 0;} 本文作者: 帐前卒 本文链接: http://chillyc.info/2010/2010-05-24-design-pattern-chain-reponsibility/ 版权声明: 本博客所有文章除特别声明外,只能复制超链接地址,且必须注明出处!