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