DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • AI-Powered Defenses Against Clickjacking in Finance
  • Scaling ML Models Efficiently With Shared Neural Networks
  • Predicting Diabetes Types: A Deep Learning Approach
  • Neural Networks: From Perceptrons to Deep Learning

Trending

  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  • A Modern Stack for Building Scalable Systems
  • Apache Doris vs Elasticsearch: An In-Depth Comparative Analysis
  • A Complete Guide to Modern AI Developer Tools
  1. DZone
  2. Data Engineering
  3. AI/ML
  4. Composite Design Pattern in Modern C++

Composite Design Pattern in Modern C++

To treat individual & group of objects in a uniform manner.

By 
Vishal Chovatiya user avatar
Vishal Chovatiya
·
Sep. 08, 20 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
11.9K Views

Join the DZone community and get the full member experience.

Join For Free

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 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 checked out my other articles on Structural Design Patterns, then here is the list:

  1.  Adapter
  2.  Bridge
  3.  Composite
  4.  Decorator
  5.  Facade
  6.  Flyweight
  7.  Proxy

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 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 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.

Objects in factory cartoon

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 of Shapes(e.g. vector<Circle>) which inherits from a collection Shape.

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

C++
 




xxxxxxxxxx
1
39


 
1
struct Shape {
2
    virtual void draw() = 0;
3
};
4

5
struct Circle : Shape {
6
    void draw() { cout << "Circle" << endl; }
7
};
8

9
struct Group : Shape {
10
    string              m_name;
11
    vector<Shape*>      m_objects;
12

13
    Group(const string &n) : m_name{n} {}
14

15
    void draw() {
16
        cout << "Group " << m_name.c_str() << " contains:" << endl;
17
        for (auto &&o : m_objects)
18
            o->draw();
19
    }
20
};
21

22
int main() {
23
    Group root("root");
24
    root.m_objects.push_back(new Circle);
25

26
    Group subgroup("sub");
27
    subgroup.m_objects.push_back(new Circle);
28

29
    root.m_objects.push_back(&subgroup);
30
    root.draw();
31

32
    return EXIT_SUCCESS;
33
}
34
/*
35
Group root contains:
36
Circle
37
Group sub contains:
38
Circle
39
*/


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.

C++
 




xxxxxxxxxx
1
35


 
1
struct Neuron {
2
    vector<Neuron*>     in, out;
3
    uint32_t            id;
4

           
5
    Neuron() {
6
        static int id = 1;
7
        this->id = id++;
8
    }
9

           
10
    void connect_to(Neuron &other) {
11
        out.push_back(&other);
12
        other.in.push_back(this);
13
    }
14

           
15
    friend ostream &operator<<(ostream &os, const Neuron &obj) {
16
        for (Neuron *n : obj.in)
17
            os << n->id << "\t-->\t[" << obj.id << "]" << endl;
18

           
19
        for (Neuron *n : obj.out)
20
            os << "[" << obj.id << "]\t-->\t" << n->id << endl;
21

           
22
        return os;
23
    }
24
};
25

           
26
int main() {
27
    Neuron n1, n2;
28
    n1.connect_to(n2);
29
    cout << n1 << n2 << endl;
30
    return EXIT_SUCCESS;
31
}
32
/* Output
33
[1]    -->    2
34
1    -->    [2]
35
*/



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.

C++
 




xxxxxxxxxx
1
23


 
1
struct NeuronLayer : vector<Neuron> {
2
    NeuronLayer(int count) {
3
        while (count-- > 0)
4
            emplace_back(Neuron{});
5
    }
6

           
7
    friend ostream &operator<<(ostream &os, NeuronLayer &obj) {
8
        for (auto &n : obj)
9
            os << n;
10
        return os;
11
    }
12
};
13

           
14
int main() {
15
    NeuronLayer l1{1}, l2{2};
16
    Neuron n1, n2;
17
    n1.connect_to(l1);  // Neuron connects to Layer
18
    l2.connect_to(n2);  // Layer connects to Neuron
19
    l1.connect_to(l2);  // Layer connects to Layer
20
    n1.connect_to(n2);  // Neuron connects to Neuron
21

           
22
    return EXIT_SUCCESS;
23
}



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.

C++
 




xxxxxxxxxx
1


 
1
Neuron::connect_to(NeuronLayer&)
2
NeuronLayer::connect_to(Neuron&)
3
NeuronLayer::connect_to(NeuronLayer&)
4
Neuron::connect_to(Neuron&)



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.

C++
 




x
87


 
1
template <typename Self>
2
struct SomeNeurons {
3
    template <typename T>
4
    void connect_to(T &other);
5
};
6

           
7
struct Neuron : SomeNeurons<Neuron> {
8
    vector<Neuron*>     in, out;
9
    uint32_t            id;
10

           
11
    Neuron() {
12
        static int id = 1;
13
        this->id = id++;
14
    }
15

           
16
    Neuron* begin() { return this; }
17
    Neuron* end() { return this + 1; }
18
};
19

           
20
struct NeuronLayer : vector<Neuron>, SomeNeurons<NeuronLayer> {
21
    NeuronLayer(int count) {
22
        while (count-- > 0)
23
            emplace_back(Neuron{});
24
    }
25
};
26

           
27
template <typename Self>
28
template <typename T>
29
void SomeNeurons<Self>::connect_to(T &other) {
30
    for (Neuron &from : *static_cast<Self *>(this)) {
31
        for (Neuron &to : other) {
32
            from.out.push_back(&to);
33
            to.in.push_back(&from);
34
        }
35
    }
36
}
37

           
38
template <typename Self>
39
ostream &operator<<(ostream &os, SomeNeurons<Self> &object) {
40
    for (Neuron &obj : *static_cast<Self *>(&object)) {
41
        for (Neuron *n : obj.in)
42
            os << n->id << "\t-->\t[" << obj.id << "]" << endl;
43

           
44
        for (Neuron *n : obj.out)
45
            os << "[" << obj.id << "]\t-->\t" << n->id << endl;
46
    }
47
    return os;
48
}
49

           
50
int main() {
51
    Neuron n1, n2;
52
    NeuronLayer l1{1}, l2{2};
53

           
54
    n1.connect_to(l1); // Scenario 1: Neuron connects to Layer
55
    l2.connect_to(n2); // Scenario 2: Layer connects to Neuron
56
    l1.connect_to(l2); // Scenario 3: Layer connects to Layer
57
    n1.connect_to(n2); // Scenario 4: Neuron connects to Neuron
58

           
59
    cout << "Neuron " << n1.id << endl << n1 << endl;
60
    cout << "Neuron " << n2.id << endl << n2 << endl;
61

           
62
    cout << "Layer " << endl << l1 << endl;
63
    cout << "Layer " << endl << l2 << endl;
64

           
65
    return EXIT_SUCCESS;
66
}
67
/* Output
68
Neuron 1
69
[1]    -->    3
70
[1]    -->    2
71

           
72
Neuron 2
73
4    -->    [2]
74
5    -->    [2]
75
1    -->    [2]
76

           
77
Layer 
78
1    -->    [3]
79
[3]    -->    4
80
[3]    -->    5
81

           
82
Layer 
83
3    -->    [4]
84
[4]    -->    2
85
3    -->    [5]
86
[5]    -->    2
87
*/



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 both Neuron & 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

  1.  Reduces code complexity by eliminating many loops over the homogeneous collection of objects.
  2.  This intern increases the maintainability & testability of code with fewer chances to break existing running & tested code.
  3.  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.

Design neural network Object (computer science) Machine learning

Published at DZone with permission of Vishal Chovatiya. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • AI-Powered Defenses Against Clickjacking in Finance
  • Scaling ML Models Efficiently With Shared Neural Networks
  • Predicting Diabetes Types: A Deep Learning Approach
  • Neural Networks: From Perceptrons to Deep Learning

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!