设计模式[14]-Composite

本文介绍了一种使用C++实现的组合模式,通过该模式可以构造树形对象结构并进行遍历。文章展示了Component基类及其派生类Leaf和Composite的具体实现方式,通过递归手段构建复杂的对象结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Type: Structural Composite: 通过递归手段来构造诸如文件系统之类的树形的对象结构;Composite模式所代表的数据构造是一群具有统一接口界面的对象集合,并可以通过一个对象来访问所有的对象(遍历)。


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

class Component
{
public:
    virtual void operation()=0;
    virtual void add(Component* c){};
    virtual void remove(Component* c){};
    virtual Component* getChild(int i){};
};

class Leaf: public Component
{
public:
    void operation()
    {
        cout<<"Leaf"<<endl;
    };
};

class Composite: public Component
{
public:
    void operation()
    {
        cout<<"Composite"<<endl;
    };
    void add(Component* c)
    {
        mChildren.insert(mChildren.begin(), c);
    };
    void remove(Component* c)
    {        
        vector<Component*>::iterator it;
        for(it = mChildren.begin(); it < mChildren.end(); it++)
            if(*it == c)
            {
                mChildren.erase(it);
                break;
            }                
    };
    Component* getChild(int i)
    {
        if(i < 0 || i >= mChildren.size())
            return NULL;
        return mChildren[i]; 
    };
private:
    vector<Component*> mChildren;
};

void printComponent(Component* pComponent)
{
     pComponent->operation();
     if(!dynamic_cast<Composite*>(pComponent))
         return;     
     int i=0;
     Component* childComponent;
     while(childComponent = pComponent->getChild(i++))
     {
         printComponent(childComponent);
     };
};
int main()
{
    Leaf *pLeaf1 = new Leaf();
    Leaf *pLeaf2 = new Leaf();

    Composite* pComposite = new Composite;
    pComposite->add(pLeaf1);
    pComposite->add(pLeaf2);
    Composite* pComposite2 = new Composite;
    pComposite2->add(pComposite);
    printComponent(pComposite2);

    system("pause");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值