You are on page 1of 2

Chain of Responsibility Tip i scop: ablon comportamental; evit dependen a unui emi tor de un anumit receptor cu ajutorul unei

colec ii de receptori (ce ar putea fiecare gestiona o cerere); Solu ie: se construie te un lan (pipeline) de noduri ce pot gestiona o cerere; emi torul lanseaz cererea (launch-and-leave); cererea este pasat din nod n nod pan cnd un anumit nod o gestioneaz ;

Exemplu:
#include <iostream> #include <vector> #include <string> #include <ctime> using namespace std; class Base { Base* nextLink; public: Base() : nextLink(NULL) {} void setNext(Base* link){ nextLink = link; } void addLink(Base* link) { if ( nextLink != NULL ) { nextLink->addLink(link); } else { nextLink = link; } } // the "chain" method in the base class always delegates to the next obj virtual void handleRequest(const string& request) { nextLink->handleRequest(request); }

}; class Handler1: public Base { public: /*virtual*/ void handleRequest( const string& request) { // don't handle requests 3 times out of 4 if ( rand() % 3 ) { cout << "Handler1 passsed ..."; // delegate to the base class Base::handleRequest(request); } else { cout << "Handler1 handled " << request << "\n"; } } }; class Handler2: public Base { public: /*virtual*/ void handleRequest(const string& request) { if ( rand() % 3 ) { cout << "Handler2 passsed ..."; Base::handleRequest(request); } else { cout << "Handler2 handled " << request << "\n"; } } }; class Handler3: public Base { public: /*virtual*/ void handleRequest(const string& request) { if ( rand() % 3 ) { cout << "Handler3 passsed ..."; Base::handleRequest(request); } else { cout << "Handler3 handled " << request << "\n"; } } }; int main() { srand(time(0)); Handler1 root; Handler2 two; root.addLink(&two); Handler3 thr; root.addLink(&thr); thr.setNext(&root); root.handleRequest("doThis"); root.handleRequest("doThat"); root.handleRequest("doAnotherThing"); root.handleRequest("doSomething"); root.handleRequest("doAnything"); return 0; }

You might also like