code refactoring: fix memory leaks, code style, etc.

This commit is contained in:
Jakub Vojvoda
2019-01-31 19:57:40 +01:00
parent a8681552c4
commit a0b0ea4f8e
24 changed files with 960 additions and 566 deletions

View File

@@ -16,13 +16,19 @@
* defines an interface for all objects in the composition
* both the composite and the leaf nodes
*/
class Component {
class Component
{
public:
virtual Component *getChild(int) { return 0; }
virtual void add(Component *) { /* ... */ }
virtual void remove(int) { /* ... */ }
virtual ~Component() {}
virtual Component *getChild( int )
{
return 0;
}
virtual void add( Component * ) { /* ... */ }
virtual void remove( int ) { /* ... */ }
virtual void operation() = 0;
};
@@ -31,28 +37,44 @@ public:
* defines behavior of the components having children
* and store child components
*/
class Composite : public Component {
class Composite : public Component
{
public:
Component *getChild(int index) {
return children.at(index);
}
void add(Component *component) {
children.push_back(component);
}
void remove(int index) {
children.erase(children.begin() + index);
}
void operation() {
for (unsigned int i = 0; i < children.size(); i++) {
children.at(i)->operation();
~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;
std::vector<Component*> children;
};
/*
@@ -60,11 +82,15 @@ private:
* defines the behavior for the elements in the composition,
* it has no children
*/
class Leaf : public Component {
class Leaf : public Component
{
public:
Leaf(int i) : id(i) {}
void operation() {
Leaf( const int i ) : id( i ) {}
~Leaf() {}
void operation()
{
std::cout << "Leaf "<< id <<" operation" << std::endl;
}
@@ -76,12 +102,14 @@ private:
int main()
{
Composite composite;
for (unsigned int i = 0; i < 10; i++) {
composite.add(new Leaf(i));
for ( unsigned int i = 0; i < 5; i++ )
{
composite.add( new Leaf( i ) );
}
composite.remove( 0 );
composite.operation();
return 0;
}