forked from JakubVojvoda/design-patterns-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathComposite.cpp
115 lines (95 loc) · 1.83 KB
/
Composite.cpp
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
103
104
105
106
107
108
109
110
111
112
113
114
115
/*
* C++ Design Patterns: Composite
* Author: Jakub Vojvoda [github.com/JakubVojvoda]
* 2016
*
* Source code is licensed under MIT License
* (for more details see LICENSE)
*
*/
#include <iostream>
#include <vector>
/*
* Component
* defines an interface for all objects in the composition
* both the composite and the leaf nodes
*/
class Component
{
public:
virtual ~Component() {}
virtual Component *getChild( int )
{
return 0;
}
virtual void add( Component * ) { /* ... */ }
virtual void remove( int ) { /* ... */ }
virtual void operation() = 0;
};
/*
* Composite
* defines behavior of the components having children
* and store child components
*/
class Composite : public Component
{
public:
~Composite()
{
for ( unsigned int i = 0; i < children.size(); i++ )
{
delete children[ i ];
}
}
Component *getChild( const unsigned int index )
{
return children[ index ];
}
void add( Component *component )
{
children.push_back( component );
}
void remove( const unsigned int index )
{
Component *child = children[ index ];
children.erase( children.begin() + index );
delete child;
}
void operation()
{
for ( unsigned int i = 0; i < children.size(); i++ )
{
children[ i ]->operation();
}
}
private:
std::vector<Component*> children;
};
/*
* Leaf
* defines the behavior for the elements in the composition,
* it has no children
*/
class Leaf : public Component
{
public:
Leaf( const int i ) : id( i ) {}
~Leaf() {}
void operation()
{
std::cout << "Leaf "<< id <<" operation" << std::endl;
}
private:
int id;
};
int main()
{
Composite composite;
for ( unsigned int i = 0; i < 5; i++ )
{
composite.add( new Leaf( i ) );
}
composite.remove( 0 );
composite.operation();
return 0;
}