Composite pattern describes as group of objects that will be treated in same manner as single instance of object. Main logic behind a composite pattern is “composing” the objects in tree structures and represent it in part or whole hierarchies. Full implementation of composite pattern give clients treats individual objects and it compositions equivalently.
Questions: When to use composite pattern:
This pattern could be use whenever clients want to disregard difference between individual and compositions of the objects. Let’s take example when you are doing coding and find that you are using many objects in same way and those have nearly matching code which handles each of them then it would be good choice to use composite design pattern. It would be less complex for this situation to treat primitives and composites as identical.
See example below example where it implements graphic class which could be either ellipse or composition of several graphics. Here every graphic could be printed.
- Create Component Interface:
- Composite class:
- Create Leaf:
- Client Class:
- That’s it. Below is list of all design patterns link:
- Chain of Responsibility
- Template Method