patterns

The Composite Pattern

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 500x500Modernes C++ Mentoring

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (open)
  • "Generic Programming (Templates) with C++": October 2024
  • "Embedded Programming with Modern C++": October 2024
  • "Clean Code: Best Practices for Modern C++": March 2025
  • Do you want to stay informed: Subscribe.

     

    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.

    Related Patterns

    • 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, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, 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, Stephen Kelley, Kyle Dean, Tusar Palauri, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery,and Matt Godbolt.

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

    My special thanks to Embarcadero
    My special thanks to PVS-Studio
    My special thanks to Tipi.build 
    My special thanks to Take Up Code
    My special thanks to SHAVEDYAKS

    Modernes C++ GmbH

    Modernes C++ Mentoring (English)

    Do you want to stay informed about my mentoring programs? Subscribe Here

    Rainer Grimm
    Yalovastraße 20
    72108 Rottenburg

    Mobil: +49 176 5506 5086
    Mail: schulung@ModernesCpp.de
    Mentoring: www.ModernesCpp.org

    Modernes C++ Mentoring,

     

     

    0 replies

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply

    Your email address will not be published. Required fields are marked *