Question
Create an Interface or Abstract base Class 'Shape'.
* Implement three concrete Shapes: 'Circle', 'Rectangle', 'Triangle'.
* Apply the visitor pattern to your data model.
* Write an AreaVisitor that computes the area of the shapes.
* Write a main that makes an arbitrary instance of a data model and apply the AreaVisitor
Solution
/*
============================================================================
Author : James Chen
Email : a.james.chen@gmail.com
Description : Implementation of Visitor Design Pattern
Created Data : 23-01-2014
Last Modified :
============================================================================
*/
#include <iostream>
#include "AreaVisitor.h"
int main(int argc, char* argv[])
{
Circle circle(2);
Triangle triangle(3, 4, 5);
Rectangle rectangle(5, 3);
Circle circle1(1);
Triangle triangle1(5, 4, 5);
Rectangle rectangle1(5, 6);
Shape* shapes[] = {&circle, &triangle, &rectangle, &circle1, &triangle1, &rectangle1};
AreaVisitor areaVisitor;
for(int i = 0; i < sizeof(shapes) / sizeof(shapes[0]); ++ i){
areaVisitor.VisitShape(shapes[i]);
cout << shapes[i]->Info() << endl;
cout << "Area = " << areaVisitor.Area() << endl;
cout << "-------------------" << endl;
}
// Test for invalid arguments
try{
Circle circle(-2);
}
catch(exception e){
cout << e.what() << endl;
}
try{
Rectangle rect(-2, 2);
}
catch(exception e){
cout << e.what() << endl;
}
try{
Triangle triangle(-2, 2, 2);
}
catch(exception e){
cout << e.what() << endl;
}
return 0;
}
Output
Circle(2.000000)
Area = 12.5664
-------------------
Triangle( 3.000000, 4.000000, 5.000000)
Area = 6
-------------------
Rectangle(5.000000, 3.000000)
Area = 15
-------------------
Circle(1.000000)
Area = 3.14159
-------------------
Triangle( 5.000000, 4.000000, 5.000000)
Area = 9.16515
-------------------
Rectangle(5.000000, 6.000000)
Area = 30
-------------------
Circle(-2.000000) is not valid.
The radius of a circle must be greater than 0
Rectangle(-2.000000, 2.000000) is not valid.
The width and height of a rectangle must be greater than 0.
Triangle(-2.000000, 2.000000, 2.000000) is not valid.
The size of any edge must be greater than 0
The sum of size of any two edges must be greater than the size of the third edge
Press any key to continue . . .