feat: implement Composite

main
mandlm 2024-03-14 20:25:58 +01:00
parent 4b82ca17ac
commit 68da0a4b6c
Signed by: mandlm
GPG Key ID: 4AA25D647AA54CC7
1 changed files with 52 additions and 0 deletions

View File

@ -1,8 +1,60 @@
#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;
}