Composite design pattern is used to handle primitive and composite objects uniformly.
Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual
objects and compositions of objects uniformly.
The intent is to compose the object to present part-whole hierarchy and handle both primitive and composite object uniformly.
The primitive and composite objects have to be handled differently. To distinguish these objects for manipulation
increases the complexity.
Come up with a way to manipulate the primitive and composite object uniformly.
That means both the primitive and composite object have to be handled in similar manner.
Where it is applicable?
When part-whole hierarchy of object has to be represented.
Wherever primitive and composite objects have to be handled in similar manner.
Directories and Files in File system are the best example.
This is the UML structure of Composite design pattern-
Component class provides the interface Operation().
Concrete classes Leaf and Composite implements the method Operation().
How they work together?
Composite has instance of the class Component. It has objects which can be Leaf and Composite as well. It traverses
them and does the operation on all the elements it has composed, either primitive or composite.
The method Add(), Remove() and GetChild() can be provided in Component or Composite, its transparency vs safety.
Providing it in Component class makes it transparent and providing it in Composite class makes it safe.
So you can see both the primitive and composite objects are handled in similar manner.
Suresh Kumar Srivastava is founder of online learning site coursegalaxy.com and author of popular books "C In Depth",
"Data Structures Through C In Depth". He has 18+ years experience in industry and worked on architecture and design of
multiple products. This article is from his courses on Design Patterns.
CourseGalaxy is focused on transformation of Engineering graduate to Software Engineer to fill the gap
between education and industry and provide the training on specific problems of industry to enhance the skills
of Engineers in industry to do their job appropriately.