Decorator Design Pattern in Modern C++
To facilitates the additional functionality to objects.
Join the DZone community and get the full member experience.Join For Free
In software engineering, Structural Design Patterns deal with the relationship between objects and classes i.e. how objects and classes interact or build a relationship in a manner suitable to the situation. The Structural Design Patterns simplify the structure by identifying relationships. In this article, we're going to take a look at the not so complex yet subtle design pattern that is Decorator Design Pattern in Modern C++ due to its extensibility and testability. It is also known as a Wrapper.
The code snippets you see throughout this series of articles are simplified, not sophisticated. So you often see me not using keywords like
public(while inheritance) just to make code compact and consumable(most of the time) in single standard screen size. I also prefer
struct instead of
class just to save line by not writing "
public:" sometimes and also miss virtual destructor, constructor, copy constructor, prefix
std::, deleting dynamic memory, intentionally. I also consider myself a pragmatic person who wants to convey an idea in the simplest way possible rather than the standard way or using jargon.
If you stumbled here directly, then I would suggest you go through What is design pattern? first, even if it is trivial. I believe it will encourage you to explore more on this topic.
All of this code you encounter in this series of articles are compiled using C++20(though I have used Modern C++ features up to C++17 in most cases). So if you don't have access to the latest compiler you can use https://wandbox.org/ which has preinstalled boost library as well.
To facilitates the additional functionality to objects.
Sometimes we have to augment the functionality of existing objects without rewrite or altering existing code, just to stick to the Open-Closed Principle. This also preserves the Single Responsibility Principle to have extra functionality on the side.
Decorator Design Pattern Examples in C++And to achieve this we have two different variants of Decorator Design Pattern in C++:
- Dynamic Decorator: Aggregate the decorated object by reference or pointer.
- Static Decorator: Inherit from the decorated object.
So, we have a hierarchy of two different
Circle), and we want to enhance this hierarchy by adding color to it. Now we're suddenly not going to create two other classes e.g. colored circle and a colored square. That would be too much and ultimately isn't a scalable option.
Rather we can just have
ColoredShape as follows.
Why this is a dynamic decorator?
Because you can instantiate the
ColoredShape at runtime by providing needed arguments. In other words, you can decide at runtime that which
Square) is going to be coloured.
You can even mix the decorators as follows:
Limitation of Dynamic Decorator
If you look at the definition of
Circle, You can see that the circle has a method called
resize(). we can not use this method as we did aggregation on-base interface
Shape & bound by the only method exposed in it.
The dynamic decorator is great if you don't know which object you are going to decorate and you want to be able to pick them at runtime but sometimes you know the decorator you want at compile time in which case you can use a combination of C++ templates & inheritance.
As you can see we can now call the
resize() method which was the limitation of Dynamic Decorator. You can even mix the decorators as we did earlier.
So essentially what this example demonstrates is that if you're prepared to give up on the dynamic composition nature of the decorator and if you're prepared to define all the decorators at compile time you get the added benefit of using inheritance.
And that way you actually get the members of whatever object you are decorating being accessible through the decorator and mixed decorator.
Functional Approach to Decorator Design Pattern Using Modern C++
Up until now, we were talking about the Decorator Design Pattern which decorates over a class but you can do the same for functions. Following is a typical logger example for the same:
Above example may seem a bit complex to you but if you have a clear understanding of variadic temple then it won't take more than 30 seconds to understand what's going on here.
Benefits of Decorator Design Pattern
- Decorator facilitates augmentation of the functionality for an existing object at run-time & compile time.
- Decorator also provides flexibility for adding any number of decorators, in any order & mixing it.
- Decorators are a nice solution to permutation issues because you can wrap a component with any number of Decorators.
- It is a wise choice to apply the Decorator Design Pattern for already shipped code. Because it enables backward compatibility of application & less unit level testing as changes do not affect other parts of code.
Summary by FAQs
When to use the Decorator Design Pattern?
-- Employ the Decorator Design Pattern when you need to be able to assign extra behaviours to objects at runtime without breaking the code that uses these objects.
-- When the class has final keyword which means the class is not further inheritable. In such cases, the Decorator Design Pattern may come to rescue.
What are the drawbacks of using the Decorator Design Pattern?
-- Decorators can complicate the process of instantiating the component because you not only have to instantiate the component but wrap it in a number of Decorators.
-- Overuse of Decorator Design Pattern may complicate the system in terms of both i.e. Maintainance & learning curve.
Difference between Adapter & Decorator Design Pattern?
-- Adapter changes the interface of an existing object
-- Decorator enhances the interface of an existing object
Difference between Proxy & Decorator Design Pattern?
-- Proxy provides a somewhat same or easy interface
-- Decorator provides enhanced interface
Published at DZone with permission of Vishal Chovatiya. See the original article here.
Opinions expressed by DZone contributors are their own.