This repository has been archived on 2024-12-15. You can view files and clone it, but cannot push or open issues or pull requests.
CppPatterns/Composite/main.cpp

61 lines
1.1 KiB
C++

#include <iostream>
#include <string>
#include <vector>
class Node {
public:
virtual ~Node() = default;
virtual void print() const = 0;
};
class InnerNode : public Node {
private:
std::string name_;
std::vector<Node *> children_;
public:
InnerNode(std::string_view name) : name_(name) {}
void addNode(Node *node) { children_.push_back(node); }
void print() const override {
std::cout << name_ << " (inner)" << std::endl;
for (auto child : children_) {
child->print();
}
}
};
class Leaf : public Node {
private:
std::string name_;
public:
Leaf(std::string_view name) : name_(name) {}
void print() const override { std::cout << name_ << " (leaf)" << std::endl; }
};
int main(int argc, char *argv[]) {
std::cout << "Composite" << std::endl;
InnerNode tree("root");
InnerNode left("left"), right("right");
Leaf leaf1("leaf 1"), leaf2("leaf 2"), leaf3("leaf 3"), leaf4("leaf 4");
tree.addNode(&left);
tree.addNode(&right);
left.addNode(&leaf1);
left.addNode(&leaf2);
right.addNode(&leaf3);
right.addNode(&leaf4);
tree.print();
return EXIT_SUCCESS;
}