Solution: Decorator Design Pattern
Get a detailed explanation of the solution to the decorator design exercise.
We'll cover the following...
Solution
Press + to interact
#include <iostream>#include <string>struct Shape{virtual std::string str() = 0;virtual float getWidth() = 0;virtual float getHeight() = 0;};class Rectangle : public Shape{float width = 10.0f;float height = 5.0f;public:std::string str() override{return std::string("A rectangle of width ") + std::to_string(width) + " and height " + std::to_string(height);}float getWidth() override{return width;}float getHeight() override{return height;}};class MarginShape : public Shape{float margin;Shape& shape;float width;float height;public:MarginShape(float m, Shape& s) : shape(s){margin = m;width = shape.getWidth() + 2*margin;height = shape.getHeight() + 2*margin;}std::string str() override{return shape.str() + std::string(" with a margin of ") + std::to_string(margin);}float getWidth() override{return width;}float getHeight() override{return height;}};class BorderShape : public Shape{float border;Shape& shape;float width;float height;public:BorderShape(float b, Shape& s) : shape(s){border = b;width = shape.getWidth() + 2*border;height = shape.getHeight() + 2*border;}std::string str() override{return shape.str() + std::string(" which has a border of size ") + std::to_string(border);}float getWidth() override{return width;}float getHeight() override{return height;}};int main(){Rectangle rectangle;MarginShape marginShape(2.0f, rectangle);BorderShape borderShape(1.0f, marginShape);std::cout << rectangle.str() << " Width: " << rectangle.getWidth() << " and Height: " << rectangle.getHeight() << std::endl;std::cout << marginShape.str() << " Width: " << marginShape.getWidth() << " and Height: " << marginShape.getHeight() << std::endl;std::cout << borderShape.str() << " Width: " << borderShape.getWidth() << " and Height: " << borderShape.getHeight() << std::endl;}