C++ 组合模式

本文深入探讨了C++中的组合模式,这是一种结构型设计模式,它允许我们以统一的方式处理单个对象和对象集合。通过使用组合模式,可以将部分与整体的关系表示得更加清晰,实现部分与整体的递归结构,并且客户可以一致地处理单个对象和组合对象。文章详细解释了组合模式的原理、实现方式以及在实际编程中的应用案例。

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


#include <iostream>
#include <list>
#include <string>
#include <algorithm>
using namespace std;
class IFile
{
public:

    virtual ~IFile(){}
    virtual void show() = 0;
    virtual void add(IFile *f) = 0;
    virtual void remove(IFile *f) = 0;
    virtual list<IFile*>* Getchild() = 0;
    virtual string getname() = 0;
};
class File:public IFile
{
public:
    File(string name)
    {
        m_name  = name;
    }
    string getname()
    {
        return m_name;
    }

    void show()
    {
        cout<<m_name<<endl;
    }
    void add(IFile *f)
    {

    }
    void remove(IFile *f)
    {

    }
    list<IFile*>* Getchild()
    {
        return nullptr;
    }

private:
    string m_name;
};


class Dir:public IFile
{
public:
    Dir(string name)
    {
        m_name  = name;
        _list = new list<IFile*>;

    }
    ~Dir()
    {
      if(_list!=NULL)
      {

        while(!_list->empty())
        {
            delete *(_list->begin());
            _list->erase(_list->begin());

        }
        delete _list;
      }
    }
    string getname()
    {
        return m_name;
    }
    void show()
    {
        cout<<m_name<<endl;

    }
    void add(IFile *f)
    {
        _list->push_back(f);
    }
    void remove(IFile *f)
    {
        _list->remove(f);
    }
    list<IFile*>* Getchild()
    {
        return _list;
    }

private:
    string m_name;
    list<IFile*>* _list;
};
void func(IFile* f1)
{
    IFile *f2 = new Dir("电影");
    IFile *f3 = new Dir("游戏");
    IFile *f4 = new Dir("哈利波特");
    IFile *f5 = new Dir("学习");


    IFile *w1 = new File("哈利波特1");
    IFile *w2 = new File("哈利波特3");
    IFile *w3 = new File("大黄蜂.mp4");
    IFile *w4 = new File("疯狂的外星人.mp4");
    IFile *w5 = new File("DOTA2.exe");
    IFile *w6 = new File("剑指offer.pdf");


    f1->add(f2);
    f1->add(f3);
    f1->add(f5);

    f2->add(f4);
    f2->add(w3);
    f2->add(w4);
    f3->add(w5);
}
bool mycompare(IFile* left,IFile* right)
{
    return left->getname()<right->getname();
}

void show(IFile *file,int level)
{
    for(int i=0;i<level;i++)
        cout<<"----";

    file->show();
    list<IFile*>* m_list = file->Getchild();
    if(m_list!=NULL)
    {
        m_list->sort(mycompare);
        list<IFile*>::iterator it = m_list->begin();
        while(it!=m_list->end())
        {
            show(*it,level+1);
            ++it;
        }
    }


}

int main()
{
    IFile *f1 = new Dir("D盘");
    func(f1);
    show(f1,0);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值