组合模式¶
组合模式(Composite Pattern),依据树形结构来组合对象,用来表示部分以及整体层次。它创建了对象组的树形结构。
- Component 是抽象类,Composite 和 Leaf 继承自 Component。
- Composite 作为树的非叶子节点,内部以 1 对 n (容器)的组合方式包含了其他树节点(可以是 Leaf、Composite)。(用于递归组合数结构)
- Leaf 作为树的叶子节点。(用于树终结递归)
- 示例代码:以下示例可以调用
print()
一个接口,打印其所有子树信息。
// composite.cpp
#include <iostream>
#include <string>
#include <vector>
class Graphic {
public:
virtual void print() const = 0;
virtual ~Graphic() {}
};
class GraphicComposite : public Graphic {
std::vector<const Graphic*> children; // (1)
const std::string& name;
public:
explicit GraphicComposite(const std::string& n): name(n){}
void print() const override { // (5)
std::cout << name << " ";
for (auto c: children) c->print();
}
void add(const Graphic* component) { // (2)
children.push_back(component);
}
void remove(const Graphic* component) { // (3)
std::erase(children, component);
}
};
class Ellipse: public Graphic {
private:
const std::string& name;
public:
explicit Ellipse(const std::string& n): name (n) {}
void print() const override { // (4)
std::cout << name << " ";
}
};
int main(){
std::cout << '\n';
const std::string el1 = "ellipse1";
const std::string el2 = "ellipse2";
const std::string el3 = "ellipse3";
const std::string el4 = "ellipse4";
Ellipse ellipse1(el1);
Ellipse ellipse2(el2);
Ellipse ellipse3(el3);
Ellipse ellipse4(el4);
const std::string graph1 = "graphic1";
const std::string graph2 = "graphic2";
const std::string graph3 = "graphic3";
GraphicComposite graphic1(graph1);
GraphicComposite graphic2(graph2);
GraphicComposite graphic(graph3);
graphic1.add(&ellipse1);
graphic1.add(&ellipse2);
graphic1.add(&ellipse3);
graphic2.add(&ellipse4);
graphic.add(&graphic1);
graphic.add(&graphic2);
graphic1.print();
std::cout << '\n';
graphic2.print();
std::cout << '\n';
graphic.print(); // (6)
std::cout << '\n';
graphic.remove(&graphic1);
graphic.print(); // (7)
std::cout << "\n\n";
}
- 可能的输出
graphic1 ellipse1 ellipse2 ellipse3
graphic2 ellipse4
graphic3 graphic1 ellipse1 ellipse2 ellipse3 graphic2 ellipse4
graphic3 graphic2 ellipse4