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

6,388 thoughts on “Composite Design Pattern: Structural patterns

  1. Can I show my graceful appreciation and give my value on really good
    stuff and if you want to with no joke truthfully see Let me tell you
    a brief about how to become a millionaire I am always here for yall you know that right?

  2. Even an adverse effect as common as fatigue can result in a patient missing or incorrectly administering a dose viagra prank porn 5 G Injection, powder, for solution Intramuscular; Intravenous; Parenteral 750 MG Injection, powder, for suspension Intramuscular 750 MG 3ML Tablet, coated Oral 125 MG Injection, powder, for solution Intramuscular; Intravenous 750 mg 1 Injection, powder, for solution Intravenous 1

  3. Thank you for another magnificent post. Where else could anybody get
    that kind of information in such a perfect way of writing?
    I’ve a presentation subsequent week, and I’m on the look for
    such info.

  4. Unquestionably believe that which you stated. Your favorite reason seemed to be on the net the easiest
    factor to take into account of. I say to you, I certainly get annoyed at the same time as
    other folks think about concerns that they plainly don’t
    understand about. You controlled to hit the nail upon the highest as well as
    defined out the whole thing without having side-effects , other people can take a
    signal. Will probably be back to get more. Thank you

  5. Pingback: 1conspire
  6. Hey There. I discovered your weblog the usage of msn. That is a really
    smartly written article. I will be sure to bookmark it and
    come back to read extra of your helpful info. Thank you for the post.

    I will certainly return.

  7. I do not even understand how I finished up here, but I
    thought this post was great. I do not realize who you might be but definitely you are going to a famous
    blogger in case you are not already 😉 Cheers!

    Here is my web site :: conyers amc

  8. hey there and thank you for your information – I’ve certainly picked up something new from right
    here. I did however expertise some technical
    issues using this site, as I experienced to reload the web site lots of times previous to I could get
    it to load correctly. I had been wondering if your
    web hosting is OK? Not that I am complaining, but slow
    loading instances times will sometimes affect your placement in google and could damage your quality score if advertising and marketing with Adwords.
    Anyway I am adding this RSS to my e-mail and could look out
    for a lot more of your respective interesting content.
    Ensure that you update this again soon.

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

  10. I constantly intend to ensure I reveal my appreciation for
    my kid’s teachers in a unique method. This article has some excellent
    pointers for thank you presents.

  11. Howdy, There’s no doubt that your blog might be having internet browser
    compatibility problems. Whenever I look at your site
    in Safari, it looks fine however when opening in IE, it has some overlapping issues.
    I merely wanted to give you a quick heads up! Apart from that, excellent site!

  12. Hello, you used to write wonderful, but the last few posts have
    been kinda boring? I miss your tremendous writings.
    Past several posts are just a little bit out of track!
    come on!

  13. Ferrocene indole hybrids 8 14 and their corresponding organic analogues 1 7 showed only moderate antimalarial activities, while ferrocene indole hybrids 11 and 12 showed excellent in vitro activities against the A549 human carcinoma cell line, with IC 50 values of 5 and 7 ОјM respectively side effects doxycycline monohydrate

  14. Do you have a spam problem on this site; I also am a blogger,
    and I was curious about your situation; many of us have developed some nice methods and we are looking to exchange techniques with other folks, be sure to shoot me an e-mail if interested.

  15. Разработчики позаботились о безопасности пользователей, создав надежную систему безопасности.

    My homepage leonbets

  16. My spouse and I absolutely love your blog and find nearly all of your post’s to be what precisely I’m looking
    for. Do you offer guest writers to write content to suit
    your needs? I wouldn’t mind publishing a post or
    elaborating on some of the subjects you write related to here.
    Again, awesome website!

  17. Thanks for your personal marvelous posting!
    I quite enjoyed reading it, you could be a great author. I
    will make certain to bookmark your blog and will often come back later on. I
    want to encourage that you continue your great job, have
    a nice afternoon!

  18. Howdy are using WordPress for your blog platform?
    I’m new to the blog world but I’m trying to get started and create my own. Do you
    require any coding knowledge to make your own blog? Any help would be really

  19. As a moms and dad, it’s so essential to me to reveal my recognition for my
    kid’s teachers. This write-up has some excellent gift

  20. A person essentially help to make seriously
    posts I’d state. This is the very first time I frequented your website page and thus far?
    I amazed with the research you made to create this particular post amazing.

    Excellent task!

  21. Hi there! This is kind of off topic but I need some help from an established blog.

    Is it difficult to set up your own blog? I’m not very techincal but
    I can figure things out pretty quick. I’m thinking about creating
    my own but I’m not sure where to begin. Do you have any ideas or
    suggestions? Cheers

  22. I’m curious to find out what blog system you are working with?
    I’m having some small security issues with my latest site and I would
    like to find something more risk-free. Do you have any suggestions?

  23. Yall already know how much iwant to give a subscribe
    or a follow for this. Let me tell you my ways on really amazing stuff
    and if you want to know whats up? I will share info about how to make
    passive income check and follow me bros!

  24. My spouse and I absolutely love your blog and find a lot of your post’s to
    be exactly I’m looking for. can you offer guest
    writers to write content available for you?
    I wouldn’t mind publishing a post or elaborating on many of the subjects
    you write with regards to here. Again, awesome website!

  25. Simply want to say your article is as astounding. The clearness
    in your post is just excellent and i can assume you are an expert on this
    subject. Well with your permission allow me to grab your RSS feed to
    keep up to date with forthcoming post. Thanks a million and please keep up
    the rewarding work.

  26. I believe people who wrote this needs true loving because
    it’s a blessing. So let me give back and give my value on change your life and if you want to with no joke truthfully see I will share info about how to get connected to girls for free Don’t forget..
    I am always here for yall. Bless yall!

  27. Undeniably believe that which you said.
    Your favorite reason appeared to be on the internet the simplest
    factor to have in mind of. I say to you,
    I certainly get annoyed whilst people consider worries that
    they just do not recognize about. You controlled to hit the nail upon the top and also defined out the whole thing
    without having side effect , other folks could take a signal.

    Will likely be back to get more. Thank you

  28. I was curious if you ever considered changing the structure of your website?
    Its very well written; I love what youve got to say.
    But maybe you could a little more in the way of content
    so people could connect with it better. Youve
    got an awful lot of text for only having one or 2 pictures.

    Maybe you could space it out better?

  29. This is the perfect web site for anybody who would like
    to understand this topic. You know a whole lot its almost hard to
    argue with you (not that I actually would want to…HaHa).
    You definitely put a new spin on a subject that has been written about for decades.
    Excellent stuff, just great!

  30. Yall already know how much iwant to give a subscribe or
    a follow for this. Let me tell you really amazing stuff and if you want to know whats
    up? I will share info about how to find hot girls for free check and follow me bros!

  31. Very nice post. I just stumbled upon your weblog and
    wished to say that I’ve truly enjoyed surfing around your
    blog posts. After all I’ll be subscribing to your feed and I
    hope you write again very soon!

  32. 와~ 이건 진짜 대박이네요. 제가 그토록 원하던 정보들이네.
    저또한 똑같이 해줘야되겠는데, 저도 알려드리고 싶은데요 그거아시나 혹시 쉽게 돈 만들기 말도 안되는 이야기라고는 하지만 이렇게 쉽게 알수 없는 내용를 저만 알고 있는 방법이 있는데 제가 나눠드리겠습니다.
    한번 믿어보시고 확인 해보시죠!

  33. Amazing blog! Do you have any tips and hints for aspiring writers?
    I’m hoping to start my own blog soon but I’m a little lost on everything.
    Would you recommend starting with a free platform
    like WordPress or go for a paid option? There are so many choices out there
    that I’m totally confused .. Any tips? Thanks a lot!

  34. I think this is one of the most significant information for me.

    And i am glad reading your article. But wanna remark on some general
    things, The web site style is great, the articles
    is really excellent : D. Good job, cheers

  35. Write more, thats all I have to say. Literally,
    it seems as though you relied on the video to make your point.
    You obviously know what youre talking about, why throw away your intelligence on just posting videos to your blog when you could be
    giving us something enlightening to read?

  36. Let me give you a thumbs up man. Can I finally give back amazing values
    and if you want to have a checkout and also share valuable info about
    how to make passive income yalla lready know follow me my fellow commenters!.

  37. Thanks for every other informative site.
    The place else may I get that kind of information written in such
    an ideal method? I’ve a project that I am simply now operating on, and I’ve been on the look out for such

  38. Hello there, I discovered your site by the use of Google while searching
    for a comparable matter, your site came up, it seems
    good. I’ve bookmarked it in my google bookmarks.

    Hi there, simply changed into aware of your weblog through
    Google, and located that it is truly informative. I am gonna watch out for
    brussels. I will appreciate should you proceed this in future.
    A lot of other folks will probably be benefited out of your writing.

  39. Hi there! I know this is kinda off topic but I was wondering which blog platform are
    you using for this website? I’m getting sick and tired of
    Wordpress because I’ve had issues with hackers and I’m looking at options for another platform.
    I would be great if you could point me in the direction of a good

  40. If you are going for best contents like myself, just go to
    see this web page all the time for the reason that it provides feature contents, thanks

  41. This is really interesting, You are a very skilled blogger.

    I’ve joined your feed and look forward to
    seeking more of your great post. Also, I have shared
    your web site in my social networks!

  42. I got this web page from my buddy who told me regarding this site and at the moment this time I am visiting this website and reading very informative articles at this time.

  43. You have made some good points there. I checked on the net to
    learn more about the issue and found most individuals will go along with your views on this web site.

  44. Hello! Quick question that’s entirely off topic.
    Do you know how to make your site mobile friendly? My site looks weird when viewing from
    my iphone. I’m trying to find a theme or plugin that might
    be able to correct this issue. If you have any recommendations, please share.
    Appreciate it!

  45. I needed to thank you for this excellent read!!
    I certainly loved every bit of it. I have got you book marked to check out new stuff you post…

  46. Simply wish to say your article is as astonishing.

    The clearness in your submit is just cool
    and that i can assume you are a professional in this subject.
    Well together with your permission allow me to take hold of your RSS feed to stay up to date with approaching post.
    Thanks 1,000,000 and please carry on the rewarding work.

  47. I am extremely impressed with your writing skills and also with the layout on your weblog.
    Is this a paid theme or did you customize it yourself?
    Anyway keep up the nice quality writing, it is rare to see a nice blog like this one today.