GoF describes the Composite Design Pattern as “Compose objects into a tree structure to represent part-whole hierarchies. Composite lets the client treat individual objects and compositions of objects uniformly”. This seems over-complicated to me. So, I would not go into tree-leaf kind of jargon. Rather I directly saw you 2 or 3 different ways to implement Composite Design Pattern in Modern C++. But in simple words, the Composite Design Pattern is a Structural Design Pattern with a goal to treat the group of objects in the same manner as a single object.
By the way, If you haven’t check out my other articles on Structural Design Patterns, then here is the list:
The code snippets you see throughout this series of articles are simplified not sophisticated. So you often see me not using keywords like override
, final
, public
(while inheritance) just to make code compact & 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 Jargons.
Note:
- 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.
Intent
To treat individual & group of objects in a uniform manner.
- So what is it all about and why do we need it. Well, we know that objects typically use other objects fields or properties or members through either inheritance or composition.
- For example, in drawing applications, you have a
Shape
(e.g.Circle
) that you can draw on the screen but you can also have a group ofShape
s(e.g.vector<Circle>
) which inherits from a collectionShape
. - And they have certain common API which you can then call on one or the other without knowing in advance whether you’re working with a single element or with the entire collection.
Composite Design Pattern Examples in C++
- So if you think about an application such as PowerPoint or any kind of vector drawing application you know that you can draw & drag individual shapes around.
- But you can also group shapes together. And when you group several shapes together you can treat them as if they were a single shape. So you can grab the entire thing and also drag it and resize it and whatnot.
- So, we’re going to implement the Composite Design Pattern around this idea of several different shapes.
Classical Composite Design Pattern
|
|
Composite Design Pattern using Curiously Recurring Template Pattern(CRTP)
- As you’ve probably noticed machine learning is a really hot topic nowadays. And part of the machine learning mechanics is to use of neural networks so that’s what we’re going to take a look at now.
|
|
- As you can see we have a neuron structure which has connections to other neurons that modelled as vectors of pointers for input-output neuron connection. This is a very basic implementation and it works just fine as long as you just have individual neurons. Now the one thing that we haven’t accounted for is what happens when you have more than one neuron or group of neurons to connect.
- Let’s suppose that we decide to make a neuron layer and now a layer of neurons is basically like a collection.
|
|
- Now as you probably guessed if you were to implement this head-on you’re going to have a total of four different functions. i.e.
- So this is state-space explosion & permutation problem and it’s not good because we want a single function that enumerable both the layer as well as individual neurons.
|
|
- As you can see we have covered all four different permutation scenarios using a single
SomeNeurons::connect_to
method with the help of CRTP. And bothNeuron
&NeuronLayer
conforms to this interface via self templatization. - Curiously Recurring Template Pattern comes handy here & has very straight implementation rule i.e. separate out the type-dependent & independent functionality and bind type independent functionality with the base class using self-referencing template.
- I have written a separate article on Advanced C++ Concepts & Idioms including CRTP.
Benefits of Composite Design Pattern
- Reduces code complexity by eliminating many loops over the homogeneous collection of objects.
- This intern increases the maintainability & testability of code with fewer chances to break existing running & tested code.
- The relationship is described in the Composite Design Pattern isn’t a subclass relationship, it’s a collection relationship. Which means client/API-user does not need to care about operations(like translating, rotating, scaling, drawing, etc.) whether it is a single object or an entire collection.
Summary by FAQs
When should I use the Composite Design Pattern?
- You want clients to be able to ignore the difference between the group of objects and individual objects.
- When you find that you are using multiple objects in the same way, and looping over to perform a somewhat similar action, then composite is a good choice.
What is the common example of the Composite Design Pattern?
- File & Folder(collection of files): Here File is a single class. Folder inherits File and holds a collection of Files.
What is the difference between Decorator & Composite Design Pattern?
- Decorator works on enhancing interface.
- Composition works to unify interfaces for single & group of objects.