实现要点,component,composite,leaf这三个类都要实现,
其它的都需要继承自两个子类
#include <cstdlib>
#include <iostream>
#include <string>
#include <list>
using namespace std;
class Component
{
protected:
int value;
string name;
public:
Component(){}
Component(int n):value(n){}
virtual ~Component(){cout<<"Component 基类析构"<<endl;}
virtual int GetValue() = 0;
virtual void Add(Component* pCom) = 0;
virtual void Remove(Component* pCom) = 0;
};
class Composite:public Component
{
list<Component*> ComList;
public:
~Composite(){
cout<<name<<"析构Composite"<<endl;
list<Component*>::iterator it = ComList.begin();
list<Component*>::iterator itEnd = ComList.end();
int dwRes = 0;
for(;it != itEnd;it++){
delete *it;
}
ComList.clear();
}
virtual int GetValue(){
list<Component*>::iterator it = ComList.begin();
list<Component*>::iterator itEnd = ComList.end();
int dwRes = 0;
for(;it != itEnd;it++){
dwRes += (*it)->GetValue();
}
return dwRes;
}
virtual void Add(Component* pCom){ComList.push_back(pCom);}
virtual void Remove(Component* pCom){
list<Component*>::iterator it = ComList.begin();
list<Component*>::iterator itEnd = ComList.end();
for(;it != itEnd;it++){
if(*it = pCom){
delete pCom;
break;
}
}
ComList.erase(it);
}
};
class Leaf:public Component
{
public:
Leaf(int n):Component(n){}
~Leaf(){cout<<name<<"析构Leaf"<<endl;}
virtual int GetValue(){return value;}
virtual void Add(Component* pCom){assert(false);}
virtual void Remove(Component* pCom){assert(false);}
};
class Computer:public Composite
{
public:Computer(){name = "Computer";}
};
class Host:public Composite
{public:Host(){name = "Host";}};
class Display:public Leaf
{
public:
Display(int n):Leaf(n){name = "Display";}
};
class KeyBoard:public Leaf
{
public:
KeyBoard(int n):Leaf(n){name = "KeyBoard";}
};
class Cpu:public Leaf
{
public:
Cpu(int n):Leaf(n){name = "Cpu";}
};
class MainBoard:public Leaf
{
public:
MainBoard(int n):Leaf(n){name = "MainBoard";}
};
class Memory:public Leaf
{
public:
Memory(int n):Leaf(n){name = "Memory";}
};
int main(int argc, char *argv[])
{
Component* pPc = new Computer();
Component* pHost = new Host();
Component* pCpu = new Cpu(500);
Component* pMainBoard = new MainBoard(500);
Component* pMemory1 = new Memory(160);
Component* pMemory2 = new Memory(160);
Component* pDisplay = new Display(900);
Component* pKeyBoard = new KeyBoard(100);
pHost->Add(pMainBoard);
pHost->Add(pMemory1);
pHost->Add(pMemory2);
pHost->Add(pCpu);
pPc->Add(pHost);
pPc->Add(pDisplay);
pPc->Add(pKeyBoard);
cout<<"最后的整机价格:"<<pPc->GetValue()<<endl;
delete pPc;
system("PAUSE");
return EXIT_SUCCESS;
}