The Composite Pattern
This post is a cross-post from www.ModernesCpp.com.
The Composite Pattern allows you to compose objects into tree structures and treat the individual object and composite objects uniformly.
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
Use Case
Structure
Component
Leaf
Composite
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.
Modernes C++ Mentoring
Get the invitation to the one-hour presentation of my mentoring program "Fundamentals for C++ Professionals" including Q&A.
Do you want the invitation to the Zoom meeting? ???Write an e-mail with the header First or Second to [email protected].
?
If you cannot make it, here is the last recorded introduction.
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:
领英推荐
?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
What are the pros and cons of the Composite Pattern?
Pros and Cons
Let me start with the benefits.
Pros
Cons
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 it 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, Louis St-Amour, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Neil Wang, 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, and Wolfgang Fütterer.
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
My special thanks to PVS-Studio
?
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