Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- using namespace std;
- typedef const char * String;
- #define MAX_CHILDREN 10
- class Component{
- public:
- String name;
- Component(String name):name(name){}
- virtual void Add(Component *c)=0;
- virtual void Remove(Component *c)=0;
- virtual void Display(int depth)=0;
- };
- class Composite:public Component{
- Component *children[MAX_CHILDREN];
- public:
- Composite(String name):Component(name){
- for(int i=0;i<MAX_CHILDREN;i++) children[i]= 0;
- }
- ~Composite(){
- for(int i=0;i<MAX_CHILDREN;i++){
- if (children[i]) delete children[i];
- }
- }
- void Add(Component *component){
- for(int i=0;i<MAX_CHILDREN;i++){
- if(!children[i]){
- children[i] = component;
- break;
- }
- }
- }
- void Remove(Component *component){
- Component **pc;
- pc = children;
- for(int i=0;i<MAX_CHILDREN;i++){
- if (pc[i]==component){
- for(int j=i;j<(MAX_CHILDREN-1);j++){
- pc[j] = pc[j+1];
- }
- pc[MAX_CHILDREN-1] = 0;
- break;
- }
- }
- }
- void Display(int depth){
- for(int i=0;i<depth;i++) cout<<'-';
- cout<<name<<endl;
- for(int i=0;i<MAX_CHILDREN;i++){
- if (children[i]) children[i]->Display(depth+2);
- }
- }
- };
- class Leaf:public Component{
- public:
- Leaf(String name):Component(name){}
- void Add(Component *c){
- cout<<"Cannot add to a leaf"<<endl;
- }
- void Remove(Component *c){
- cout<<"Cannot remove from a leaf"<<endl;
- }
- void Display(int depth){
- for(int i=0;i<depth;i++) cout<<'-';
- cout<<name<<endl;}
- };
- main()
- {
- //Create a tree struct
- Component *root = new Composite("root");
- root->Add(new Leaf("Leaf A"));
- root->Add(new Leaf("Leaf B"));
- Composite *comp = new Composite("Composite X");
- comp->Add(new Leaf("Leaf XA"));
- comp->Add(new Leaf("Leaf XB"));
- root->Add(comp);
- root->Add(new Leaf("Leaf C"));
- //add and remove a leaf
- Leaf *leaf = new Leaf("Leaf D");
- root->Add(leaf);
- root->Remove(leaf);
- delete leaf;
- //recursively display tree
- root->Display(1);delete root;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement