Composite Design Pattern
Composite design pattern is used to handle primitive and composite objects uniformly.
The intent is to compose the object to present part-whole hierarchy and handle both primitive and composite object uniformly.
- Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual
objects and compositions of objects uniformly.
- The primitive and composite objects have to be handled differently. To distinguish these objects for manipulation
increases the complexity.
That means both the primitive and composite object have to be handled in similar manner.
- Come up with a way to manipulate the primitive and composite object uniformly.
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-
How they work together?
- Component class provides the interface Operation().
- Concrete classes Leaf and Composite implements the method Operation().
- 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.
Lets explore the implementation of Composite design pattern in different programming languages.
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.
Shell Scripting, SED & AWK