CompositePattern.cpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. class Component {
  5. public:
  6. virtual void Operation() { }
  7. virtual void Add(const Component& com) { }
  8. virtual void Remove(const Component& com) { }
  9. virtual Component* GetChild(int index) {
  10. return 0;
  11. }
  12. virtual ~Component() { }
  13. };
  14. class Composite :public Component {
  15. public:
  16. void Add(Component* com) {
  17. _coms.push_back(com);
  18. }
  19. void Operation() {
  20. for (auto com : _coms)
  21. com->Operation();
  22. }
  23. void Remove(Component* com) {
  24. //_coms.erase(&com);
  25. }
  26. Component* GetChild(int index) {
  27. return _coms[index];
  28. }
  29. private:
  30. std::vector<Component*> _coms;
  31. };
  32. class Leaf :public Component {
  33. public:
  34. void Operation() {
  35. cout << "Leaf::Operation..." << endl;
  36. }
  37. };
  38. int main() {
  39. Leaf *leaf = new Leaf();
  40. leaf->Operation();
  41. Composite *com = new Composite();
  42. com->Add(leaf);
  43. com->Operation();
  44. Component *leaf_ = com->GetChild(0);
  45. leaf_->Operation();
  46. delete leaf;
  47. delete com;
  48. return 0;
  49. }