组合模式--Composite

假设有一个公司,下面有直属人事部,直属餐饮部,和一个子公司,但是子公司也有自己的直属人事部,直属餐饮部。要清楚的是子公司包括其直属子部门在一起也属于总公司的一个部门。即:子公司也是一种部门。

#include <iostream>
#include <vector>
#include <string>
#include <iterator>
using namespace std;
//公司基类
class Company
{
public:
	Company(){}
	Company(string s):companyName(s){}
	virtual ~Company(){}
	virtual void show(int depth)=0;
	virtual void add(Company*){};
protected:
	string companyName;
};
class ConcreteCompany:public Company
{
public:
	ConcreteCompany(string s):Company(s){}
	virtual void add(Company *com)
	{
		vec_com.push_back(com);
	}
	virtual void show(int depth)
	{
		for(int i=0;i<depth;i++)
			cout<<"-";
		cout<<companyName<<endl;
		for(vector<Company*>::iterator iter=vec_com.begin();iter!=vec_com.end();iter++)
		{
			(*iter)->show(depth+2);
		}
	}
private:
	vector<Company*> vec_com;
};
//餐饮部门
class FoodCompany:public Company
{
public:
	FoodCompany(string s):Company(s){}
	void show(int depth)
	{
		for(int i=0;i<depth;i++)
			cout<<"-";
		cout<<companyName<<endl;
	}
};
//人事部门
class HrCompany:public Company
{
public:
	HrCompany(string s):Company(s){}
	void show(int depth)
	{
		for(int i=0;i<depth;i++)
			cout<<"-";
		cout<<companyName<<endl;
	}
};
int main()
{
	Company *root=new ConcreteCompany("总公司");
	Company *food=new FoodCompany("总公司餐饮部");
	Company *hr=new HrCompany("总公司人事部");
	root->add(food);
	root->add(hr);

	Company *subRoot1=new ConcreteCompany("分公司1");
	Company *sub1food=new FoodCompany("分公司1餐饮部");
	Company *sub1hr=new HrCompany("分公司1人事部");
	subRoot1->add(sub1food);
	subRoot1->add(sub1hr);

	Company *subRoot2=new ConcreteCompany("分公司2");
	Company *sub2food=new FoodCompany("分公司2餐饮部");
	Company *sub2hr=new HrCompany("分公司2人事部");
	subRoot2->add(sub2food);
	subRoot2->add(sub2hr);

	root->add(subRoot1);
	root->add(subRoot2);

	root->show(0);
}


你可能感兴趣的:(组合模式--Composite)