#ifndef COMPONENT_H
#define COMPONENT_H
class Component
{
public:
/** Default constructor */
Component();
/** Default destructor */
virtual ~Component();
virtual void Operation()=0;
virtual void Add(Component* pCom)=0;
virtual void Remove(Component* pCom)=0;
virtual Component* GetChild(int iCompID)=0;
protected:
private:
};
#endif // COMPONENT_H
#include "Component.h"
Component::Component()
{
//ctor
}
Component::~Component()
{
//dtor
}
#ifndef COMPOSITE_H
#define COMPOSITE_H
#include "Component.h"
#include <list>
#include <algorithm>
using namespace std;
class Composite : public Component
{
public:
/** Default constructor */
Composite();
/** Default destructor */
virtual ~Composite();
void Operation();
void Add(Component* pCom);
void Remove(Component* pCom);
Component* GetChild(int iCompID);
protected:
private:
list<Component*> m_pComponent;
};
#endif // COMPOSITE_H
#include "Composite.h"
#include <windows.h>
#include <iostream>
using namespace std;
Composite::Composite()
{
//ctor
}
Composite::~Composite()
{
for(list<Component*>::iterator it=m_pComponent.begin();it!=m_pComponent.end();it++)
{
if (NULL!=*it)
{
delete *it;
*it=NULL;
}
}
}
void Composite::Operation()
{
for(list<Component*>::iterator it=m_pComponent.begin();it!=m_pComponent.end();it++)
{
(*it)->Operation();
}
}
void Composite::Add(Component* pCom)
{
if (NULL!=pCom)
{
m_pComponent.push_back(pCom);
}
}
void Composite::Remove(Component* pCom)
{
if (NULL!=pCom)
{
m_pComponent.remove(pCom);
}
}
Component* Composite::GetChild(int iCompID)
{
list<Component*>::iterator it;
int i=0;
for(it=m_pComponent.begin();it!=m_pComponent.end();it++,i++)
{
if (i==iCompID)
{
return *it;
}
}
return NULL;
}
#ifndef LEAF_H
#define LEAF_H
#include "Component.h"
#include <tchar.h>
class Leaf : public Component
{
public:
/** Default constructor */
Leaf();
/** Default destructor */
virtual ~Leaf();
Leaf(TCHAR* pName);
void Operation();
void Add(Component* pCom);
void Remove(Component* pCom);
Component* GetChild(int iCompID);
protected:
private:
TCHAR m_sName[20];
};
#endif // LEAF_H
#include "Leaf.h"
#include <windows.h>
#include <iostream>
using namespace std;
Leaf::Leaf()
{
memset(m_sName,0,20);
}
Leaf::Leaf(TCHAR* pName)
{
memset(m_sName,0,20);
CopyMemory(m_sName,pName,20);
cout<<"创建"<<m_sName<<endl;
}
Leaf::~Leaf()
{
cout<<"解散"<<m_sName<<endl;
}
void Leaf::Operation()
{
cout<<m_sName<<"运作当中"<<endl;
}
void Leaf::Add(Component* pCom)
{
}
void Leaf::Remove(Component* pCom)
{
}
Component* Leaf::GetChild(int iCompID)
{
}
#include <iostream>
using namespace std;
#include "Component.h"
#include "Composite.h"
#include "Leaf.h"
int main()
{
Component* pZCom=new Composite();
Component* pFCom=new Leaf("分公司A");
Component* pFCom2=new Leaf("分公司B");
pZCom->Add(pFCom);
pZCom->Add(pFCom2);
pZCom->Operation();
delete pZCom;
return 0;
}