适用于用共通的接口处理文件和由文件组成的文件夹等类似情形,把个体和集合做相同的处理
#include "stdafx.h"
#include <vector>
#include<iostream>
using namespace std;
class company
{
public:
company(string name) :mName(name) {}
~company() {}
virtual void add(company*pCom) = 0;
virtual void remove(company*pCom) = 0;
virtual void operation() = 0;
virtual company* getChildbyIndex(int index) { return NULL; }
string& getName()
{
return mName;
}
private:
string mName;
};
class apartment : public company
{
public:
apartment(string name):company(name) {};
~apartment() {};
void operation()
{
cout << "--";
cout << getName().c_str() << endl;
}
void add(company*pCom){}
void remove(company*pCom) {}
private:
};
class composite : public company
{
public:
composite(string name):company(name) {};
~composite()
{
}
void add(company*pCom) {
if (pCom) {
mVecCom.push_back(pCom);
}
}
void remove(company* pCom)
{
if (!mVecCom.empty())
{
auto it = mVecCom.begin();
while (it != mVecCom.end())
{
if (*it == pCom)
{
it = mVecCom.erase(it);
}
else
{
it++;
}
}
}
}
void operation()
{
cout << getName().c_str() << endl;
for (int i = 0; i < (int)mVecCom.size(); i++)
{
cout << "--";
mVecCom[i]->operation();
}
}
company* getChildbyIndex(int index)
{
company* pRet = NULL;
if (index < 0 || index >= (int)mVecCom.size())
{
pRet = NULL;
}
else
{
pRet = mVecCom[index];
}
return pRet;
}
private:
std::vector<company*> mVecCom;
};
int main()
{
composite mC("of");
composite mSc("ofSh");
composite mSN("ofnc");
company* aHr = new apartment("Hr");
company* aTec = new apartment("Tec");
company* aHa = new apartment("Ha");
mSc.add(aHr);
mSc.add(aTec);
mSc.add(aHa);
company* aHr2 = new apartment("Hr2");
company* aTec2 = new apartment("Tec2");
company* aHa2 = new apartment("Ha2");
mSN.add(aHr2);
mSN.add(aTec2);
mSN.add(aHa2);
mC.add(&mSc);
mC.add(&mSN);
mC.operation();
cin.get();
return 0;
}