设计模式--组合模式

    组合模式:又叫部分整体模式,属于结构型模式。
    基本原理:以树形的结构将相似的对象组合起来。
    主要流程:
            1.创建对象
            2.在对象中设置用来存放下一级相似对象的数据结构。
            3.在对象中设置增删改查等功能。
    注意:这种模式和数据结构中的树形结构相似

 

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

class Employee
{
private:
    string name;
    string dept;
    string salary;
    vector<Employee*> subordinates;

public:
        Employee(){}
        Employee(string name,string dept,string salary):name(name),dept(dept),salary(salary)
        {
            this->subordinates = vector<Employee*>();
        }

        void add(Employee* e)
        {
            this->subordinates.push_back(e);
        }
        void removeSub(Employee *e)
        {
            vector<Employee*>::iterator it;
            for (it = subordinates.begin(); it != subordinates.end(); ++it)
            {
                if (e->getName() == (*it)->getName())
                {
                    subordinates.erase(it);
                    break;
                }
            }
        }
        vector<Employee*> getSubordinates()
        {
            return subordinates;
        }
        string getName()
        {
            return name;
        }
        string tostring()
        {
            return "Employee :[ Name : " + name + ", dept : " + dept + ", salary : "+ salary + " ]";
        }
};

int main()
{
    Employee * CEO = new Employee("ll","CEO","30000");
    Employee *headSales = new Employee("aa","Head Sales","20000");
    Employee *headMarketing = new Employee("Michel","Head Marketing", "20000");

    Employee *clerk1 = new Employee("Laura","Marketing", "10000");
    Employee *clerk2 = new Employee("Bob","Marketing", "10000");

    Employee *salesExecutive1 = new Employee("Richard","Sales", "10000");
    Employee *salesExecutive2 = new Employee("Rob","Sales", "10000");
    Employee *salesExecutive3 = new Employee("Rob2","Sales", "10000");

    CEO->add(headSales);
    CEO->add(headMarketing);

    headSales->add(salesExecutive1);
    headSales->add(salesExecutive2);
    headSales->add(salesExecutive3);

    headMarketing->add(clerk1);
    headMarketing->add(clerk2);

    cout<<CEO->tostring()<<endl;
    for (size_t i = 0; i < CEO->getSubordinates().size() ;++i)
    {
        Employee * emp = CEO->getSubordinates().at(i);
        cout<<emp->tostring()<<endl;
        vector<Employee*> emp1 = emp->getSubordinates();
        for (size_t i = 0; i < emp1.size() ;++i)
        {
            cout<<emp1.at(i)->tostring()<<endl;
        }
    }

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值