现在的位置: 首页 > 自动控制 > 工业·编程 > 正文

代码版设计模式8:组合模式【结构型】

2013-02-25 12:10 工业·编程 ⁄ 共 1700字 ⁄ 字号 暂无评论

#include <iostream>
#include <string>
#include <vector>
using namespace std;

//
struct ICompany
{
public:
    ICompany(string name) : m_name(name) { }
    virtual ~ICompany() { }

    virtual void Add(ICompany *pCompany) = 0;
    virtual void Show(int nDepth) = 0;

protected:
    string m_name;
};

class CActualCompany : public ICompany
{
public:
    CActualCompany(string name) : ICompany(name) { }
    virtual ~CActualCompany() { }

    virtual void Add(ICompany *pCompany)
    {
        m_pCompanyVec.push_back(pCompany);
    }
    virtual void Show(int nDepth)
    {
        for (int i=0;i<nDepth;i++)
            cout<<"-";
        cout<<m_name<<endl;

        vector<ICompany*>::iterator ite = m_pCompanyVec.begin();
        for(; m_pCompanyVec.end() != ite; ite++)
        {
            (*ite)->Show(nDepth+2);
        }
    }
private:
    vector<ICompany*> m_pCompanyVec;
};

class CFinanceDepartment : public ICompany
{
public:
    CFinanceDepartment(string name) : ICompany(name) { }
    virtual ~CFinanceDepartment() { }

    virtual void Add(ICompany *pCompany) { }

    virtual void Show(int nDepth)
    {
        for (int i=0;i<nDepth;i++)
            cout<<"-";
        cout<<m_name<<endl;
    }
};

class CHRDepartment : public ICompany
{
public:
    CHRDepartment(string name) : ICompany(name) { }
    virtual ~CHRDepartment() { }

    virtual void Add(ICompany *pCompany) { }

    virtual void Show(int nDepth)
    {
        for (int i=0;i<nDepth;i++)
            cout<<"-";
        cout<<m_name<<endl;
    }
};

//
void main()
{
    CActualCompany company("A");
   
    CActualCompany subCompany1("A1");
    CFinanceDepartment subFinance1("Finance A1");
    CHRDepartment subHR1("HR A1");
    subCompany1.Add(&subFinance1);
    subCompany1.Add(&subHR1);
    company.Add(&subCompany1);

    CFinanceDepartment finace("Finance A");
    company.Add(&finace);

    CHRDepartment hr("HR A");
    company.Add(&hr);

    company.Show(0);
   
}

给我留言

留言无头像?