Search⌘ K

Decorator Design Pattern Example

Explore the decorator design pattern in C++ by examining an example where a concrete decorator class inherits from the component class directly. Understand how to implement abstract classes with pure virtual functions, extend behaviors by composing objects, and apply margins to shapes through code. This lesson helps you deepen your knowledge of flexible software design techniques.

We'll cover the following...

In the previous lesson, we saw a coding example of a decorator design pattern. Here, we’ll look at another example of a decorator design pattern. But this time, we’ll make a small change in our code: we won’t create a decorator. Instead, the concrete decorator class will inherit the component class directly.

Example

C++
#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;
}
};
int main(){
Rectangle rectangle;
MarginShape marginShape(2.0f, rectangle);
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;
}
Decorator design pattern example

Code explanation

Let’s look at the code line by line:

...