The Composite Pattern

Contents[Show]

The Composite Pattern allows you to compose objects into tree structures and treat the individual object and composite objects uniformly.

patterns

The Composite Pattern is similar to the Decorator Pattern I presented in my last post.  Both patterns are of structural nature. The main difference is that the Composite Pattern composites tree structures, but the Decorator Pattern only has one object.

Here are more details about the Composite Pattern.

Composite Pattern

Purpose

  • Combines objects into tree structures to handle them uniformly

Use Case

  • Represents part/whole hierarchies
  • Clients can treat single and composite objects equally

Structure

CompositePattern

Component

  • Defines the interface
  • Defines an interface so that the Composite (parent) can access its Component's child  (optionally)

Leaf

  • Represents the singular object
  • Implements the interface

Composite

  • Represents the composite object
  • Defines member functions to manipulate its children

When you perform an operation on the tree structure, the operation can be performed on a leaf node or a composite node. The operation is directly performed if it is a leaf node. The operation is delegated to all children components if it is a composite node. A composite node has a list of children and member functions to add or remove those. Consequentially, each component (leaf node or composite node) can handle the operation appropriately.

 

Rainer D 6 P2 540x540Modernes C++ Mentoring

Stay informed about my mentoring programs. Subscribe for the news.

 

 

Example

// composite.cpp

#include <iostream>
#include <string>
#include <vector>

class Graphic {
 public:
    virtual void print() const = 0;
    virtual ~Graphic() {} 
};

class GraphicComposite : public Graphic {
    std::vector<const Graphic*> children;                          // (1)
    const std::string& name;
 public:
    explicit GraphicComposite(const std::string& n): name(n){}
    void print() const override {                                  // (5)
        std::cout << name << " ";
        for (auto c: children) c->print();
    }

    void add(const Graphic* component) {                           // (2)
        children.push_back(component);
    }

    void remove(const Graphic* component) {                        // (3)
        std::erase(children, component);
    }
};

class Ellipse: public Graphic {
 private:
    const std::string& name;
 public:
    explicit Ellipse(const std::string& n): name (n) {}
    void print() const override {                                 // (4)
        std::cout << name << " ";
    }
};

int main(){

    std::cout << '\n';

    const std::string el1 = "ellipse1";
    const std::string el2 = "ellipse2";
    const std::string el3 = "ellipse3";
    const std::string el4 = "ellipse4";

    Ellipse ellipse1(el1);
    Ellipse ellipse2(el2);
    Ellipse ellipse3(el3);
    Ellipse ellipse4(el4);

    const std::string graph1 = "graphic1";
    const std::string graph2 = "graphic2";
    const std::string graph3 = "graphic3";

    GraphicComposite graphic1(graph1);
    GraphicComposite graphic2(graph2);
    GraphicComposite graphic(graph3);

    graphic1.add(&ellipse1);
    graphic1.add(&ellipse2);
    graphic1.add(&ellipse3);

    graphic2.add(&ellipse4);

    graphic.add(&graphic1);
    graphic.add(&graphic2);

    graphic1.print();
    std::cout << '\n';

    graphic2.print();
    std::cout << '\n';

    graphic.print();                                       // (6)

    std::cout << '\n';

    graphic.remove(&graphic1);
    graphic.print();                                       // (7)

    std::cout << "\n\n";

}

In this example Graphic defines the interface for all concrete components.  GraphicComposite stands for the composite node and Ellipse stands for the leaf node. GraphicComposite holds its children in a std::vector<const Graphic*> (line 1), and supports operations to add and remove children (lines 2 and 3). 

Each component has to implement the pure virtual function print. The Ellipse displays it name (line 4). The GraphicComposite also displays its name but, additionally, delegates the show call to its children (line 5).

The main program creates a tree structure with the root graphic. First, the tree graphic is displayed with the subtree graphic1 (line 6) and then without it (line 7).

The following screenshot shows the output of the program:
 

composite

 

Known Uses

Applying an algorithm such as find or find_if on a container of the Standard Template Library can be regarded as a simplified application of the Composite Pattern. This is particularly true if the container is an ordered associative container like std::map.

  • The Decorator Pattern is structurally similar to the composite. The main difference is that the Decorator Pattern has only one child. Additionally, the Decorator Pattern adds new responsibility to an object, while the Composite Pattern sums up the results of its children. 
  • The Iterator Pattern is typically used to traverse the components of the tree.
  • The Visitor Pattern encapsulates operations in objects applied to the components of the tree.
 
What are the pros and cons of the Composite Pattern?

Pros and Cons

Let me start with the benefits.

Pros

  • Thanks to polymorphism and recursion, you can treat complex tree structures uniformly
  • It is pretty easy to extend the tree structure with new components

Cons

  • Each new operation on the component must be implemented on the leaf node and the composite node
  • The delegation of operations adds additional run-time costs

What's Next?

With the Facade Pattern, the book "Design Patterns: Elements of Reusable Object-Oriented Software" provides an additional structural pattern.  The intention of the Facade Pattern is to provide a simplified interface to a complex library or framework.

 

Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Evangelos Denaxas, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, and Phillip Diekmann.

 

Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, Ralf Abramowitsch, John Nebel, Mipko, and Alicja Kaminska.

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC Logo

 

Seminars

I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Bookable (Online)

German

Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

New

Contact Me

Modernes C++,

RainerGrimmDunkelBlauSmall

 

Mentoring

Stay Informed about my Mentoring

 

English Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Interactive Course: The All-in-One Guide to C++20

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 85

Yesterday 6417

Week 12986

Month 33733

All 10955194

Currently are 156 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments