DecoratorPattern.cpp 972 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include <iostream>
  2. using namespace std;
  3. class Component {
  4. public:
  5. virtual void Operation() = 0;
  6. virtual ~Component() { }
  7. };
  8. class ConcreteComponent :public Component {
  9. public:
  10. void Operation() {
  11. cout << "ConcreteComponent::Operation..." << endl;
  12. }
  13. };
  14. class Decorator {
  15. public:
  16. virtual void Operation() = 0;
  17. virtual void AddBehavior() = 0;
  18. virtual ~Decorator() { }
  19. };
  20. class ConcreteDecorator :public Decorator {
  21. public:
  22. ConcreteDecorator(Component *com) {
  23. _com = com;
  24. }
  25. void AddBehavior() {
  26. cout << "ConcreteDecorator::AddBehavior..." << endl;
  27. }
  28. void Operation() {
  29. cout << "ConcreteDecorator::Operation..." << endl;
  30. AddBehavior();
  31. _com->Operation();
  32. }
  33. private:
  34. Component *_com;
  35. };
  36. int main() {
  37. Component *con = new ConcreteComponent();
  38. Decorator *dec = new ConcreteDecorator(con);
  39. dec->Operation();
  40. delete con;
  41. delete dec;
  42. return 0;
  43. }