Advertisement
Guest User

CPP lists in composite design pattern

a guest
Jan 13th, 2014
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. // main.cpp
  2.  
  3. #include <iostream>
  4. #include "Composite.h"
  5.  
  6. using namespace std;
  7.  
  8. int main() {
  9.     Composite s = Composite(1,1);
  10.     Composite *enc1 = new Composite(3, 4);
  11.     Composite *enc2 = new Composite(30, 400);
  12.     Composite *enc4 = new Composite(121, 456);
  13.  
  14.     s.addChild(enc1);
  15.     s.addChild(enc2);
  16.     s.addChild(enc4);
  17.     s.removeChild(enc4);
  18.  
  19.     s.printChildren();
  20.  
  21.     return 0;
  22. }
  23.  
  24.  
  25.  
  26.  
  27. // Composite.h
  28.  
  29. #ifndef COMPOSITE_H_
  30. #define COMPOSITE_H_
  31. #include <list>
  32. class Composite {
  33. public:
  34.     Composite(int x, int y);
  35.     int x;
  36.     int y;
  37.     std::list<Composite *> children;
  38.     void addChild(Composite * enc);
  39.     void removeChild(Composite * enc);
  40.     void printChildren();
  41.  
  42.     void printSelf();
  43.     virtual ~Composite();
  44. };
  45.  
  46. #endif /* COMPOSITE_H_ */
  47.  
  48.  
  49.  
  50.  
  51. // Composite.cpp
  52.  
  53. #include "Composite.h"
  54.  
  55. #include <iostream>
  56.  
  57. Composite::Composite(int x , int y) {
  58.     this->x = x;
  59.     this->y = y;
  60. }
  61.  
  62. Composite::~Composite() {
  63.     // TODO Auto-generated destructor stub
  64. }
  65.  
  66. void Composite::addChild(Composite * enc) {
  67.     this->children.push_back(enc);
  68. }
  69.  
  70. void Composite::removeChild(Composite * enc) {
  71.     this->children.remove(enc);
  72. }
  73.  
  74. void Composite::printChildren() {
  75.  
  76.     using namespace std;
  77.     for (list<Composite*>::iterator it = this->children.begin();
  78.             it != this->children.end(); it++) {
  79.         Composite *enc = *it;
  80.         enc->printSelf();
  81.     }
  82.  
  83. }
  84.  
  85. void Composite::printSelf() {
  86.     std::cout << this->x << " " << this->y << std::endl;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement