设计模式09——组合模式

 

用例:

//composite.cpp
//组合模式:将对象组合成树形结构以表“部分-整体”的层次结构。

#include "gtest/gtest.h"
#include <string>
#include <list>

class Component
{
public:
    Component() {}
    virtual ~Component() {}

    virtual int Add(Component*) = 0;
    virtual int Remove(Component*) = 0;
    virtual int Operation() = 0;
};

class Leaf : public Component
{
public:
    Leaf(std::string n) : name(n) {}
    ~Leaf() {}

    int Add(Component* c)
    {
        return 0;
    }

    int Remove(Component* c)
    {
        return 0;
    }

    int Operation()
    {
        return int('L');
    }

private:
    std::string name;
};


class Composite : public Component
{
public:
    Composite(std::string n) : name(n) {}
    ~Composite() 
    {
        std::list<Component*>::iterator i;
        for (i = lst.begin();i != lst.end();i++)
        {
            delete *i;
        }
    }

    int Add(Component* c)
    {
        lst.push_back(c);
        return 0;
    }

    int Remove(Component* c)
    {
        lst.remove(c);
        return 0;
    }

    int Operation()
    {
        return int('C');
    }

private:
    std::string name;
    std::list<Component*> lst;
};



TEST(Composite,composite)
{
    Composite* root = new Composite("root");
    root->Add(new Leaf("Leaf A"));
    root->Add(new Leaf("Leaf B"));

    Composite* compo = new Composite("composite1");
    root->Add(new Leaf("Leaf C"));
    root->Add(new Leaf("Leaf D"));

    root->Add(compo);

    delete root;
}

 

转载于:https://www.cnblogs.com/TheImportanceOfLiving/p/8229043.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值