Skip to content

Instantly share code, notes, and snippets.

@psyomn
Last active November 14, 2015 00:35
Show Gist options
  • Save psyomn/b912bb4ae38094bd8a03 to your computer and use it in GitHub Desktop.
Save psyomn/b912bb4ae38094bd8a03 to your computer and use it in GitHub Desktop.
Simple builder example in CXX
/* Simon psyomn Symeonidis 2015
* g++ -std=c++11 example.cpp
*/
#include <iostream>
#include <string>
#include <cstddef>
using std::string;
using std::cout;
using std::endl;
class Shape {
public:
virtual int area() = 0;
virtual ~Shape() {};
string label() { return _label; }
protected:
string _label;
friend class ShapeBuilder;
};
class Rectangle : public Shape {
public:
virtual int area() {
return _x * _y;
}
private:
int _x;
int _y;
friend class ShapeBuilder;
};
class Square : public Shape {
public:
virtual int area() {
return _side * _side;
}
private:
int _side;
friend class ShapeBuilder;
};
class Circle : public Shape {
public:
virtual int area() {
return int(3.142 * (_radius * _radius));
}
private:
int _radius;
friend class ShapeBuilder;
};
class ShapeBuilder {
public:
ShapeBuilder() : _x(0), _y(0), _side(0), _radius(0) {}
ShapeBuilder* x(int __x) {
_x = __x;
return this;
}
ShapeBuilder* y(int __y) {
_y = __y;
return this;
}
ShapeBuilder* radius(int __r) {
_radius = __r;
return this;
}
ShapeBuilder* side(int __s) {
_side = __s;
return this;
}
Shape* finalize() {
if (_x != 0 && _y != 0) {
auto rect = new Rectangle();
rect->_x = _x;
rect->_y = _y;
rect->_label = "rectangle";
return rect;
}
else if (_side != 0) {
auto sqr = new Square();
sqr->_side = _side;
sqr->_label = "square";
return sqr;
}
else if (_radius != 0) {
auto circ = new Circle();
circ->_radius = _radius;
circ->_label = "circle";
return circ;
}
return nullptr;
}
private:
int _x;
int _y;
int _side;
int _radius;
};
int main(void) {
Shape
*rec = ShapeBuilder().x(10)->y(20)->finalize(),
*cir = ShapeBuilder().radius(10)->finalize(),
*sqr = ShapeBuilder().side(4)->finalize();
cout << rec->label() << " area: " << rec->area() << endl;
cout << cir->label() << " area: " << cir->area() << endl;
cout << sqr->label() << " area: " << sqr->area() << endl;
delete rec;
delete cir;
delete sqr;
return EXIT_SUCCESS;
}
/** output:
* rectangle area: 200
* circle area: 314
* square area: 16
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment