C++组合模式

组合模式

它是一种结构型设计模式,它允许将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得客户端可以统一处理单个对象和对象组合,而不需要区分它们的类型。

使用场景:

1、当需要表示对象的层次结构,并且希望对单个对象和对象组合进行统一处理时,可以使用组合模式。例如,文件系统中的文件和文件夹就可以使用组合模式来表示。
2、当希望客户端代码能够一致地处理单个对象和对象组合时,可以使用组合模式。例如,图形界面中的控件和容器就可以使用组合模式来表示。

优势:

2、客户端代码可以统一处理单个对象和对象组合,简化了代码逻辑。
3、可以方便地增加新的对象和对象组合,扩展性好。

劣势:

1、可能会导致设计过于复杂,不适合简单的对象结构。
2、可能会导致性能损失,因为需要递归遍历整个对象树。

Code

#include <iostream>
#include <vector>

class Component {
public:
    virtual void operation() = 0;
    virtual void add(Component* component) {}
    virtual void remove(Component* component) {}
    virtual Component* getChild(int index) { return nullptr; }
};

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

class Composite : public Component {
private:
    std::vector<Component*> children;
public:
    void operation() override {
        std::cout << "Composite operation" << std::endl;
        for (auto child : children) {
            child->operation();
        }
    }

    void add(Component* component) override {
        children.push_back(component);
    }

    void remove(Component* component) override {
        // remove component from children
    }

    Component* getChild(int index) override {
        if (index >= 0 && index < children.size()) {
            return children[index];
        }
        return nullptr;
    }
};

int main() {
    Composite* composite = new Composite();
    composite->add(new Leaf());
    composite->add(new Leaf());

    Composite* subComposite = new Composite();
    subComposite->add(new Leaf());
    subComposite->add(new Leaf());
    composite->add(subComposite);

    composite->operation();

    while (1);
    return 0;
}

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值