Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
127 lines (102 sloc) 5.28 KB
// Composite.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <math.h>
#include <cmath>
#include <vector>
#include <windows.h>
void DRAW_CHAR( int x, int y )
{
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), coord );
std::cout << 'O' << std::endl;
}
class IGraphic
{
public:
virtual void Draw() = 0;
virtual void Add( const std::shared_ptr<IGraphic>& c ) { }
};
class PointGraphic : public IGraphic
{
public:
int x, y;
public:
PointGraphic( int x, int y ) : x( x ), y( y ) {}
void Draw()
{
DRAW_CHAR(x, y);
}
};
class LineGraphic : public IGraphic
{
public:
int x_s, y_s, x_e, y_e;
public:
LineGraphic( int x_s, int y_s, int x_e, int y_e )
: x_s( x_s ), y_s( y_s ), x_e( x_e ), y_e( y_e ) {}
void Draw()
{
const float x_distance = x_e - x_s;
const float y_distance = y_e - y_s;
const int length = sqrt( pow(x_distance, 2) + pow(y_distance, 2) );
const float x_step = x_distance / (float)length;
const float y_step = y_distance / (float)length;
float x_cur = x_s;
float y_cur = y_s;
for ( int i = 0; i <= length; i++ )
{
DRAW_CHAR( round(x_cur), round(y_cur) );
x_cur += x_step;
y_cur += y_step;
}
}
};
class CompositeGraphic : public IGraphic
{
std::vector< std::shared_ptr<IGraphic> > components;
public:
CompositeGraphic()
{
components = std::vector< std::shared_ptr<IGraphic> >();
}
void Draw()
{
for (const std::shared_ptr<IGraphic> component : components )
component->Draw();
}
void Add(const std::shared_ptr<IGraphic>& c )
{
components.push_back( std::move(c) );
}
};
int main()
{
//Create composite for points
std::shared_ptr<IGraphic> points( new CompositeGraphic () );
//Create composite for lines
std::shared_ptr<IGraphic> lines( new CompositeGraphic() );
//Create composite for rest of containers
std::shared_ptr<IGraphic> all( new CompositeGraphic () );
//Push points
std::shared_ptr<IGraphic> p1( new PointGraphic( 5, 5 ) );
points->Add( p1 );
std::shared_ptr<IGraphic> p2( new PointGraphic( 10, 5 ) );
points->Add( p2 );
//Push lines
std::shared_ptr<IGraphic> l1 ( new LineGraphic( 5, 10, 10, 10 ) );
std::shared_ptr<IGraphic> l2( new LineGraphic( 5, 10, 7, 16 ) );
std::shared_ptr<IGraphic> l3( new LineGraphic( 8, 16, 10, 10 ) );
lines->Add( l1 );
lines->Add( l2 );
lines->Add( l3 );
//Push containers
all->Add( points );
all->Add( lines );
//Execute method which will run on all objects
all->Draw();
std::cin.get();
}
You can’t perform that action at this time.