#pragma once
#ifndef COMPOSITE_H
#define COMPOSITE_H
#include <iostream>
#include <list>
#include <algorithm>
#include <string>
using namespace std;
class Component
{
public:
Component() {}
virtual void Operation() = 0;
virtual void Add(Component* pChild) {}
virtual void Remove(Component* pChild) {}
virtual Component* GetChild(int nIndex) { return NULL; }
virtual void printname() {}
};
class Leaf :public Component
{
public:
Leaf(string name): m_name(name){}
virtual void Operation() { cout << "Operation by Leaf!" << endl; cout << m_name << endl;}
virtual void printname() { cout << m_name<< endl; }
private:
string m_name;
};
class Composite :public Component
{
public:
Composite(string name):m_name(name) {}
~Composite()
{
list<Component*>::iterator iterbegin, iterend, temp;
iterbegin = m_ListComponent.begin();
iterend = m_ListComponent.end();
while(iterbegin!= iterend)
{
temp = iterbegin;
delete(*temp);
iterbegin++;
}
}
virtual void Operation()
{
cout << "Composite----Operation" << endl;
cout << m_name << endl;
list<Component*>::iterator iterbegin, iterend;
iterbegin = m_ListComponent.begin();
iterend = m_ListComponent.end();
while (iterbegin != iterend)
{
(*iterbegin)->Operation();
iterbegin++;
}
}
virtual void Add(Component* pChild)
{
cout <<"Component----Add" << endl;
m_ListComponent.push_back(pChild);
}
virtual void Remove(Component* pChild)
{
cout << "Component----Remove" << endl;
m_ListComponent.remove(pChild);
}
virtual Component* GetChild(int nIndex)
{
cout << "Component----GetChild" << endl;
if (nIndex<=0 || nIndex>m_ListComponent.size())
{
return NULL;
}
list <Component*>::iterator iter = m_ListComponent.begin();
for (int i = 1;i<nIndex;i++)
{
iter++;
}
return *iter;
}
virtual void printname() { cout << m_name << endl; }
private:
list<Component*> m_ListComponent;
string m_name;
};
#endif // !COMPOSITE_H
#include "Composite.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
Composite* pRoot = new Composite("w1");
Leaf* pL1 = new Leaf("l1");
Leaf* pL2 = new Leaf("l2");
Leaf* pL3 = new Leaf("l3");
Leaf* pL4 = new Leaf("l4");
Leaf* pL5 = new Leaf("l5");
Leaf* pL6 = new Leaf("l6");
Composite* pC1 = new Composite("w2");
pRoot->Add(pL1);
pRoot->Add(pC1);
pRoot->Add(pL2);
pC1->Add(pL3);
pC1->Add(pL4);
pC1->Add(pL5);
pC1->Add(pL6);
pRoot->GetChild(3)->printname();
pRoot->Operation();
system("pause");
return 0;
}