-
Notifications
You must be signed in to change notification settings - Fork 0
/
composite.cc
68 lines (58 loc) · 1.34 KB
/
composite.cc
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
//
// Design pattern # composite
// Composite pattern allows you to deal individual objects.
//
// g++ -std=c++17 -Wall -Wextra -o composite composite.cc
//
#include <iostream>
#include <vector>
#include <tuple>
struct Color {
virtual void draw() = 0;
};
struct Red: Color {
void draw() override { std::cout << "Color: red" << std::endl; };
};
struct Green: Color {
void draw() override { std::cout << "Color: green" << std::endl; };
};
struct Shape {
virtual void draw(Color *color) = 0;
};
struct Triangle: Shape {
void draw(Color *color) override {
std::cout << "Shape: triangle" << std::endl;
color->draw();
}
};
struct Circle: Shape {
void draw(Color *color) override {
std::cout << "Shape: circle" << std::endl;
color->draw();
}
};
struct Picture {
void add(Shape *shape, Color *color) {
objects.push_back(std::make_tuple(shape, color));
}
void draw() {
std::cout << "Draw picture" << '\n';
for (const auto &obj: objects) {
std::get<0>(obj)->draw(std::get<1>(obj));
}
}
std::vector<std::tuple<Shape *, Color *>> objects;
};
//
// Entry function
//
int main() {
std::cout << "Design pattern # composite\n";
Picture pic;
pic.add(new Triangle(), new Red());
pic.add(new Triangle(), new Green());
pic.add(new Circle(), new Green());
pic.add(new Circle(), new Red());
pic.draw();
return 0;
}