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;
}

### C++组合模式的实现与使用 #### 1. 组合模式简介 组合模式(Composite Pattern)允许客户端一致地处理单个对象和复合对象。通过这种方式,程序能够透明地操作树形结构中的各个节点,而无需关心这些节点是叶子还是容器[^3]。 #### 2. 基本接口定义 为了使组件之间具有统一的操作接口,在C++中通常会创建一个抽象基类来声明公共的行为。这个基类既可以被具体的叶节点继承也可以被容器类型的子类所扩展: ```cpp class Component { public: virtual ~Component() {} // 定义通用的方法签名 virtual void operation() const = 0; }; ``` #### 3. 叶子组件实现 对于不包含任何子部件的对象,则可以直接派生自`Component`并提供具体的功能实现: ```cpp class Leaf : public Component { public: void operation() const override { std::cout << "Leaf Operation\n"; } }; ``` #### 4. 容器组件实现 当某个实体可能拥有多个子项时, 就应该构建一个新的类去管理这些成员变量,并重写父类方法以便于调用内部各部分的服务: ```cpp #include <vector> using namespace std; class Composite : public Component { private: vector<Component*> children_; public: void add(Component* child) { children_.push_back(child); } void remove(Component* child) { auto it = find(children_.begin(), children_.end(), child); if(it != end(children_)) children_.erase(it); } void operation() const override { cout << "Branch Operation:\n"; for(auto& comp : children_) { comp->operation(); } } }; ``` #### 5. 使用示例 最后可以通过如下方式实例化上述类来进行测试或者业务逻辑开发: ```cpp int main(){ Composite root; root.add(new Leaf()); Composite branch; branch.add(new Leaf()); branch.add(new Leaf()); root.add(&branch); root.operation(); return 0; } ``` 此代码片段展示了如何利用组合模式建立层次化的数据结构,并且可以在不影响整体架构的前提下轻松添加更多功能模块或改变现有行为。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值