Decorator.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include <stdio.h>
  2. /*
  3. * C++ Design Patterns: DECORATOR
  4. * http://www.plantuml.com/plantuml/uml/ROvDJiCm48NtFiL8BCgFGiIsYg92ovQYqZsQEWDrvTXXF4QgWFlGS_HYE97weuHPZTxxvisR146MM5kLZs3sE9qlxfVp1OnobSOu8Nv3JJ3rTUCTEO4l1Makm3V4ACQxoolrevIs64B2d6OIwkCt_-CpqZwfdW-fvrGhPD2m-KIXLtr873xhfGoVdTeKtrasBDa3JhNEZ2oxFjEFMtimBAAKyqA00Pxkkah5gYoqjvx7xBTe7soayaWNUMULHRug3_Hosz2u5U15E6g9ZBRpdebh4gX6-vsGgvWWEl2hJT82kW3h_OwDu3j1ZIPq9-G0DpuAEabmCjBfsbS4LGivi__bj6yTrkOZqgrAiT3sLvEqnTh-0G00
  5. *
  6. */
  7. #include <iostream>
  8. #include <string>
  9. class Component {
  10. public:
  11. virtual ~Component() {}
  12. virtual void operation() = 0;
  13. };
  14. class ConcreteComponent : public Component {
  15. public:
  16. ~ConcreteComponent() {}
  17. void operation() {
  18. std::cout << "Base operation for ConcreteComponent" << std::endl;
  19. }
  20. };
  21. class Decorator : public Component {
  22. public:
  23. ~Decorator() {}
  24. Decorator(Component *c) : private_component(c) {}
  25. virtual void operation() {
  26. private_component->operation();
  27. }
  28. private:
  29. Component *private_component;
  30. };
  31. class ConcreteDecoratorA : public Decorator {
  32. public:
  33. ConcreteDecoratorA(Component *c) : Decorator(c) {}
  34. void operation() {
  35. Decorator::operation();
  36. std::cout << "Augmented operation for ConcreteDecoratorA" << std::endl;
  37. }
  38. };
  39. class ConcreteDecoratorB : public Decorator {
  40. public:
  41. ConcreteDecoratorB(Component *c) : Decorator(c) {}
  42. void operation() {
  43. Decorator::operation();
  44. std::cout << "Augmented operation for ConcreteDecoratorB" << std::endl;
  45. }
  46. };
  47. int main() {
  48. Component *cc = new ConcreteComponent();
  49. ConcreteDecoratorA *cda = new ConcreteDecoratorA(cc);
  50. ConcreteDecoratorB *cdb = new ConcreteDecoratorB(cc);
  51. cda->operation();
  52. cdb->operation();
  53. }