Composite Design Pattern: Structural patterns

Share the Article


Composite design pattern is a type of structural pattern which deals with composition of objects. It treats individual objects and a composition of objects in the same manner.

Composite pattern is mainly used if we have tree like structure of our application data. This means, the application has objects in the form of root and leaves concept. The root is the composition of leaf objects as well as sub-trees. In other words, the composite pattern best suits for whole-part hierarchy where, whole consists of several part objects.


Lets us try to understand the need of composite design pattern by taking an example of an application performing the below job :

  • Firstly, get a list all the schools in the city.
  • Secondly, list all the classes in those school.
  • Finally, display all student names in every class.

Basically, for designing such an application we need to create below objects:

  • School List is one object (root level) which consists of several school objects
  • School (sub-hierarchy) is again one more object and it consists of several class objects.
  • Class is again one object sub-hierarchy which consists of several students.
  • Finally, a Student object is an independent entity.

Lets try to depict the tree diagram for above application:

composite design pattern example

Obviously, for the above application, there exists a whole-part hierarchy.

Solution without using Composite Design Pattern

One method of designing such application is without design patterns. In this case, we need to create your own class hierarchy and interfaces for managing addition of schools, classes and students. However, if there are separate interfaces for schools, classes and students, then the application shall become very complex and difficult to understand. Also, the addition of a new component also shall become difficult.

Therefore, for solving above such problem, composite pattern is the best fit.


Lets us try to design above application with Composite design pattern.

We need to follow below rules for implementing Composite design pattern:

Identify the leaf and root components

In the application, ensure that leaf components are embedded inside root components. For above application, we are having below leaf and root components.

  1. Student as leaf for Class.
  2. Class as leaf for School.
  3. School as leaf for School List.

Therefore, following is the class design for above application:

class Student //Leaf-level { }; class Class //sub-hierarchy { list<student *> m_studentList; }; class School //sub-hierarchy { list<Class*>m_classList; }; class SchoolList //root-level { list<School*>m_schoolList; };

Create common interface in all the classes

This is needed, so that user can invoke, both root as well leaf member functions through common interface. In this example, the job of the above application is to show details of every school, class and student. Hence, we add a common interface “showDetail( )” in all the classes.

class Student { public: void showDetail(); }; class Class { list<student *> m_studentList; public: void showDetail(); }; class School { list<Class*>m_classList; public: void showDetail(); }; class SchoolList { list<School*>m_schoolList; public: void showDetail(); };

Solution with Composite Design Pattern

Below is the complete code for the application which is printing all the details:

#include<iostream> //main header #include<string> //for string #include<list> //for stl list< > using namespace std;//for namespace class Student { string m_name; public: Student(string name) :m_name(name) { } void showDetail() { cout << m_name << endl; } }; class StudentList { list<Student*> s1; public: void AddStudent(Student *student) { s1.push_back(student); } void showDetail() { auto it1 = s1.begin(); auto it2 = s1.end(); cout<<" Student Details"<<endl; while (it1 != it2) { (*it1)->showDetail(); it1++; } } }; class ClassList { StudentList *listOfStudent; string m_name; public: ClassList(string name) :m_name(name) { listOfStudent=new StudentList; } void AddStudent(Student *student) { listOfStudent->AddStudent(student); } void showDetail() { cout << "Class Standard " << m_name << endl; listOfStudent->showDetail(); } ~ClassList() { delete listOfStudent; } }; class SchoolList { list<ClassList*> cl1; string m_name; public: SchoolList(string name) :m_name(name) { } void AddSchool(ClassList *schoolClassList) { cl1.push_back(schoolClassList); } void showDetail() { cout << " School Name is " << m_name << endl; auto it1 = cl1.begin(); auto it2 = cl1.end(); while (it1 != it2) { (*it1)->showDetail(); it1++; } } }; int main() //client-code { SchoolList *sl1 =new SchoolList("Green Valley"); ClassList *cl1 = new ClassList("1"); Student *s1 = new Student("jacob"); Student *s2 = new Student("Ajay"); Student *s3 = new Student("Vinay"); cl1->AddStudent(s1); cl1->AddStudent(s2); cl1->AddStudent(s3); sl1->AddSchool(cl1); sl1->showDetail(); return 0; }

As seen above with Composite design pattern, we have developed the School list application very easily. If in future, there is need to add one more list, for instance, a city list for schools, then such requestcan also be very easily added.

Pros & Cons of Composite Design Pattern


  • This pattern solves a problem related to tree structure application in very easy manner
  • It supports future enhancement for tree with less impact.


  • Composite pattern is complex to design due to his hierarchy.

Main Funda: Composite Design Pattern provides easy traversal of tree like structures.

Advanced C++ Topics

Abstract Factory Design Pattern
Singleton Design Pattern
Factory Method Design Pattern
Builder Design Pattern
Adapter Design Pattern
Prototype Design Pattern
Facade Design Pattern
Bridge Design Pattern
What is reference collapsing?

Share the Article

3,725 thoughts on “Composite Design Pattern: Structural patterns

  1. Zhao Qi peeled the cherries and said with a smile, It was the same as the Supreme Emperor back then, didn t Does Cucumber Raise Blood Sugar he Didn t the blood sugar log app Taishang Emperor also raise the outer room for a lifetime Qi Xingyun nodded, Zhao Qi knew it was good how to deal with a dog on lasix With regard to the endocrine treatment, however, some limitations of our trial deserve discussion

  2. Nice post. I learn something new and challenging on websites I stumbleupon on a daily basis. It will always be interesting to read through content from other writers and practice a little something from their sites.

  3. You’ve made some decent points there. I checked on the internet for additional information about the issue and found most individuals will go along with your views on this site.

  4. Right here is the perfect website for anybody who wants to understand this topic. You realize a whole lot its almost hard to argue with you (not that I actually will need to…HaHa). You definitely put a fresh spin on a subject that has been written about for years. Great stuff, just wonderful.

  5. After I originally commented I clicked the -Notify me when new feedback are added- checkbox and now each time a comment is added I get 4 emails with the identical comment. Is there any way you’ll be able to remove me from that service? Thanks!

  6. After I initially left a comment I appear to have clicked the -Notify me when new comments are added- checkbox and now each time a comment is added I recieve 4 emails with the same comment. There has to be an easy method you are able to remove me from that service? Thank you.

  7. I’m excited to uncover this site. I need to to thank you for your time due to this fantastic read!! I definitely really liked every bit of it and i also have you bookmarked to look at new things on your site.

  8. Hello there! This article couldn’t be written any better! Going through this article reminds me of my previous roommate! He always kept preaching about this. I will forward this post to him. Pretty sure he will have a very good read. Thanks for sharing!

  9. Aşkım Götten Bas Diyen Kuduruk. Anal. Sevgilisiyle aynı
    evde yaşayan çılgın bayan, erkek arkadaşıyla sürekli oral seks
    yapmaktan bıkar. Daha fazla tahrik olup, doruk derecesini
    artırmak için anal porno çekmeyi tercih ederler. Birlikte anal porno izle seyircileri için hd kalitede götten pozisyon kurdukları anları.

  10. xoslot is the 1st best online casino site of Thailand and Asia, especially online slots play now. and win the jackpot! Online slots, apply for unlimited withdrawal slots, up to 2 million per day xoslot

  11. The free spins offer still stands even if you use the Planet 7 Casino Deposit bonus. For example, a player can make use of the exclusive – welcome bonus and get awarded the 14 free spins every day for 14 days. Planet 7 casino free spins bonus is not available for players from the UK though they are welcome to play at the casino. Planet 7 bonus codes casino is also known to be Gaming Labs Certified, showing how it hosts a team of professionals to audit and verify gaming resources. It also has an impressive customer support team with contact channels such as an email address, a 24 7 LiveChat, and a phone address. The operator has a valid gambling licence and has been providing services for a while. Therefore, you can be confident about the legitimacy of the bonuses and promotions at Planet 7 Casino. With the increasing number of fraudulent operators out there, it is reasonable to want assurances about particular offers before using them. Planet 7 Casino is transparent with its bonus terms and conditions, which is one indicator of a legitimate operator. You only have to find the correct information. You can also verify this by claiming a Planet 7 Casino free no-deposit bonus to see how it works. So how can you protect yourself when playing poker online? The best bet is to use a well-established gambling site that doesn’t have a history of paying DDoS ransoms. After all, if an attacker knows they’ll be paid for their efforts, they’re more likely to hit the same target again. PokerStars is undoubtedly the most prestigious and popular online poker platform in the world. As a leader in online poker, the platform is home to multiple world-class poker tournaments. The site services millions of registered customers globally with the help of award-winning software. Furthermore, the platform is secure, offers player support, and is dedicated to player protection. All of this makes PokerStars a top pick for people who would want to play online poker with friends. Currently, players looking to play online poker in Ontario on licensed sites can do so on 888poker Ontario, PokerStars Ontario, BetMGM Poker Ontario, partypoker Ontario, or bwin Ontario — the latter three make up the BetMGM Ontario Network, sharing liquidity across the three skins.

  12. Home/건강/ 머리카락을 위한 코코넛
    오일의 이점은 여기에서 알 수 있습니다.
    머리카락에 코코넛 오일을 사용하는
    방법 brmp 코코넛 오일은 흰 머리의 문제를 해결하고 머리카락은 두껍고
    검은 색으로 부드럽게 될 것입니다. 그냥 이렇게

  13. Yesterday, while I was at work, my sister stole my apple ipad and tested to see if it can survive a 40 foot drop, just so she can be a youtube sensation. My iPad is now broken and she has 83 views. I know this is completely off topic but I had to share it with someone!

  14. That is a really good tip particularly to those new to the blogosphere. Simple but very accurate info… Many thanks for sharing this one. A must read article!

  15. You really make it appear so easy with your presentation however I
    in finding this matter to be really something which I believe I might
    by no means understand. It sort of feels too complicated and very wide for
    me. I’m having a look ahead for your subsequent publish, I will try
    to get the hold of it!

  16. But wanna comment on few general things, The website design and style is perfect, the subject matter is rattling good. “In business school classrooms they construct wonderful models of a nonworld.” by Peter Drucker.

  17. Thank you for every other informative web site. Where else could I am getting that kind of info written in such a perfect approach?
    I’ve a challenge that I’m simply now operating on, and I have been at the glance out for such info.

  18. Those are yours alright! . We at least need to get these people stealing images to start blogging! They probably just did a image search and grabbed them. They look good though!

  19. Having read this I thought it was very informative. I appreciate you taking the time and effort to put this article together. I once again find myself spending way to much time both reading and commenting. But so what, it was still worth it!

  20. Hi there! This post couldn’t be written any better! Reading through this post reminds me of my previous room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thank you for sharing!

  21. Thanks for another fantastic post. Where else may anyone get that type of information in such an ideal approach of writing?
    I have a presentation next week, and I’m at the search for such information.

    Here is my web blog – 2022

  22. Hi there! I could have sworn I’ve visited this
    blog before but after looking at some of the articles I realized it’s new to me.
    Nonetheless, I’m certainly pleased I stumbled upon it
    and I’ll be bookmarking it and checking back regularly!

    My web site; special

  23. Pretty nice post. I just stumbled upon your weblog and wished to say that
    I’ve really enjoyed browsing your blog posts. In any case I
    will be subscribing to your rss feed and I hope you write again very soon!

  24. wonderful publish, very informative. I ponder why the opposite experts of this sector don’t realize this. You should continue your writing. I’m confident, you’ve a huge readers’ base already!

  25. Online Casinos, die in Österreich betrieben werden, müssen entweder von der UK Gambling Commission, der Antillephone N.V., der Alderney Gambling Control Commission, der Curaçao eGaming, oder der Malta Gaming Authority lizenziert werden. Wenn der Online Casino Österreich Betreiber über keine dieser Lizenzen verfügt, sind sie wahrscheinlich nicht rechtmäßig. Der Kunden Support Um den Titel als bestes Online Casino Österreich zu erhalten, sollte der Anbieter auch einen ausgezeichneten Kunden Support haben. Da die Online Casinos meist keinen Sitz in Österreich, sondern im Ausland haben, achten Sie auch darauf, dass der Support auf Deutsch oder einer anderen Sprache, die Sie beherrschen angeboten wird. Überprüfen Sie auch über welche Wege Kontakt aufgenommen werden kann. Können Sie nur E-Mails schreiben, oder gibt es auch einen Live Chat? Die Sicherheit von Spielern wird im SlotV Online Casino ganz großgeschrieben. Wir sind nach unserem ausführlichen Test dieses Casinos davon überzeugt – SlotV ist ein seriöser Anbieter. Lizenziert ist SlotV von der MGA (Malta Gaming Authority) sowie von der Glücksspielbehörde in Curacao. Eine Lizenz der MGA ist in der Glücksspielbranche äußerst hoch angesehen, da diese Behörde besonderen Wert auf Fairness und Sicherheit in allen Online Casinos legt. Außerdem unterliegt diese Art von Lizenz sehr strengen Vorgaben, die aufmerksam verfolgt und kontrolliert werden und dazu beitragen, Spieler zu schützen und ein sicheres Umfeld für alle Spielaktivitäten zu gewährleisten. Bevor ich Ihnen alle Bonusdetails nenne, die Sie wissen müssen, möchte ich Ihnen mehr über die einzigartige Bonusstruktur erzählen. Bei SlotV gibt es eine einzigartige Bonusstruktur. Sie bietet einen Bonus für jede Art von Spieler. Es gibt einen Bonus für Anfänger, erfahrene Spieler und Highrollers. Sie können entscheiden, welche Art von Spieler Sie sind, und das Bonuspaket auswählen, das Sie verwenden möchten. Es ist möglich, zwischen den Bonuspaketen zu wechseln, wenn Sie Ihren Bonuswert erhöhen oder verringern möchten. Wenn Sie sich bei SlotV anmelden, können Sie die folgenden Pakete wählen:

  26. I really like your blog.. very nice colors & theme.
    Did you design this website yourself or did you hire someone
    to do it for you? Plz respond as I’m looking to construct my own blog and would like to find out where u
    got this from. thanks a lot

  27. The next time I read a blog, I hope that it doesnt disappoint me as much as this one. I mean, I know it was my choice to read, but I actually thought youd have something interesting to say. All I hear is a bunch of whining about something that you could fix if you werent too busy looking for attention.