欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 国际 > 组合模式(C++)

组合模式(C++)

2024/10/23 15:25:30 来源:https://blog.csdn.net/menger3388/article/details/142891200  浏览:    关键词:组合模式(C++)

定义:组合模式(Composite Pattern)是一种结构型设计模式,它将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。

应用:文件和文件夹可以看作是一种树形结构,文件夹可以包含文件和子文件夹,而文件则不包含其他对象。使用组合模式可以方便地遍历文件系统。

        代码:

// 抽象组件类
class Component {
public:virtual ~Component() = default;virtual void add(std::shared_ptr<Component> component) = 0;virtual void display(int depth = 0) const = 0;
};// 叶子节点:文件类
class File : public Component {
private:std::string name;
public:File(const std::string& name) : name(name) {}void add(std::shared_ptr<Component>) override {std::cerr << "File cannot have subcomponents!" << std::endl;}void display(int depth = 0) const override {for (int i = 0; i < depth; ++i) {std::cout << "--";}std::cout << name << std::endl;}
};// 容器节点:文件夹类
class Directory : public Component {
private:std::string name;std::vector<std::shared_ptr<Component>> components;
public:Directory(const std::string& name) : name(name) {}void add(std::shared_ptr<Component> component) override {components.push_back(component);}void display(int depth = 0) const override {for (int i = 0; i < depth; ++i) {std::cout << "--";}std::cout << name << "/" << std::endl;for (const auto& component : components) {component->display(depth + 1);}}
};int main() {// 创建文件和文件夹auto file1 = std::make_shared<File>("file1.txt");auto file2 = std::make_shared<File>("file2.txt");auto dir1 = std::make_shared<Directory>("dir1");auto dir2 = std::make_shared<Directory>("dir2");// 构建文件系统树dir1->add(file1);dir1->add(file2);dir2->add(dir1);// 显示文件系统树dir2->display();return 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com