Chain_of_responsability.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include <stdio.h>
  2. /*
  3. * C++ Design Patterns: CHAIN OF RESPONSABILITY
  4. * http://www.plantuml.com/plantuml/uml/ZP11Qnin48Nl-XKFUaXBwvhaQ9ObjMc9eJZ1oQMdejM-T5Mqqdea6KpR7vGU-YVynwgku-HGC9cBXddpFkRfCYOjAVTEJS-mkFgmNE7w4zOVRs-kLxVB-VBpykuBpgQgb74wHYoSfKzAMPyezzeGLzgtZe8V2gKc6CHkTUBNc8rXZ476-IjquzwQcyoONhzHlvwGmHjXuYFe_97qziMEYrEEphO4-o7jqBDlA56fGmXCwkFnwXYY-ZcP_7VGIVNYINt6OORdzCg7HEY8rVbuPTNKbGako4p2JhkvowmNdROUuHvhnY7uQ1lhRDfLqt6nhgPDVVJUxGRE_WqmPwUtDeXsetP3wPdG4gOGacGhHFQ4wVJ-JtcB8WUy7l7x1un6lQL1ktym8GzEV-CxE2A9jeaz_KXq6i9DtlzEnC2SK3hXmLwS4h8hj44B1fUZPPQ8q7ndYjXaYwwis3Ioyl6FtYlw5ZuagilIvTxz1G00
  5. *
  6. */
  7. #include <iostream>
  8. #include <string>
  9. class Handler {
  10. public:
  11. virtual ~Handler() {};
  12. void setSuccessor(Handler *s) {
  13. private_successor = s;
  14. }
  15. Handler* getSuccessor() {
  16. return private_successor;
  17. }
  18. virtual void handleRequest() = 0;
  19. private:
  20. Handler *private_successor;
  21. };
  22. class ConcreteHandler1 : public Handler {
  23. public:
  24. ~ConcreteHandler1() {}
  25. ConcreteHandler1(){std::cout << "Constructor ConcreteHandler1" << std::endl;}
  26. void handleRequest() {
  27. if (!this->getSuccessor()) {
  28. std::cout << "Request handled by Concrete Handler 1 // no successor" << std::endl;
  29. }
  30. else {
  31. std::cout << "Request handled by the Successor (=chain of responsability) : ";
  32. this->getSuccessor()->handleRequest();
  33. }
  34. }
  35. };
  36. class ConcreteHandler2 : public Handler {
  37. public:
  38. ~ConcreteHandler2() {}
  39. ConcreteHandler2(){std::cout << "Constructor ConcreteHandler2" << std::endl;}
  40. void handleRequest() {
  41. if (!this->getSuccessor()) {
  42. std::cout << "Request handled by Concrete Handler 2 // no successor" << std::endl;
  43. }
  44. else {
  45. std::cout << "Request handled by the Successor (=chain of responsability) : " << std::endl;
  46. this->getSuccessor()->handleRequest();
  47. }
  48. }
  49. };
  50. class Client {
  51. public:
  52. Handler *h;
  53. };
  54. int main() {
  55. Client* client = new Client();
  56. client->h = new ConcreteHandler1();
  57. Handler* h2 = new ConcreteHandler2();
  58. client->h->handleRequest();
  59. client->h->setSuccessor(h2);
  60. client->h->handleRequest();
  61. //h2->setSuccessor(client->h);
  62. client->h->handleRequest();
  63. }