-
Notifications
You must be signed in to change notification settings - Fork 2
/
UI.h
102 lines (94 loc) · 2.36 KB
/
UI.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <algorithm>
#include <iostream>
#include <list>
#include <string>
class Component {
protected:
Component *parent_;
public:
virtual ~Component() {}
void SetParent(Component *parent) {
this->parent_ = parent;
}
Component *GetParent() const {
return this->parent_;
}
virtual void Add(Component *component) {}
virtual void Remove(Component *component) {}
virtual bool IsComposite() const {
return false;
}
virtual std::string Operation() const = 0;
};
class Leaf : public Component {
public:
std::string Operation() const override {
return "Leaf";
}
};
class Composite : public Component {
protected:
std::list<Component *> children_;
public:
void Add(Component *component) override {
this->children_.push_back(component);
component->SetParent(this);
}
void Remove(Component *component) override {
children_.remove(component);
component->SetParent(nullptr);
}
bool IsComposite() const override {
return true;
}
std::string Operation() const override {
std::string result;
for (const Component *c : children_) {
if (c == children_.back()) {
result += c->Operation();
} else {
result += c->Operation() + "+";
}
}
return "Branch(" + result + ")";
}
};
void ClientCode(Component *component) {
std::cout << "RESULT: " << component->Operation();
}
void ClientCode2(Component *component1, Component *component2) {
if (component1->IsComposite()) {
component1->Add(component2);
}
std::cout << "RESULT: " << component1->Operation();
}
/*
Component *simple = new Leaf;
std::cout << "Client: I've got a simple component:\n";
ClientCode(simple);
std::cout << "\n\n";
Component *tree = new Composite;
Component *branch1 = new Composite;
Component *leaf_1 = new Leaf;
Component *leaf_2 = new Leaf;
Component *leaf_3 = new Leaf;
branch1->Add(leaf_1);
branch1->Add(leaf_2);
Component *branch2 = new Composite;
branch2->Add(leaf_3);
tree->Add(branch1);
tree->Add(branch2);
std::cout << "Client: Now I've got a composite tree:\n";
ClientCode(tree);
std::cout << "\n\n";
std::cout << "Client: I don't need to check the components classes even when managing the tree:\n";
ClientCode2(tree, simple);
std::cout << "\n";
delete simple;
delete tree;
delete branch1;
delete branch2;
delete leaf_1;
delete leaf_2;
delete leaf_3;
*/