What is a good scenario for using Composite design Pattern in Java?

Some of the good scenarios where Composite design pattern can be used are as follows:

Tree Structure: The most common use of Composite design pattern is Tree structure. If you want to represent data in a Tree data structure, Composite pattern can be used.

E.g. In an Organization, to a Manager has Employees. But Manager is also an Employee. If we start from CEO level, there is one big tree for the whole organization structure. Under that big tree there are many sub-trees. This can be easily represented with Composite design pattern.

Recursion: Another use of Composite design pattern is Recursion. If we have a Recursion based algorithm, we need data to be passed to algorithm in a data structure that treats individual objects and compositions at each level of recursion uniformly.
E.g. To implement a recursive Polynomial Solving algorithm, we can use Composite design pattern to store the intermediate results.

Graphics: Another good use of Composite design pattern is in Graphics. We can group shapes inside a composite and make higher-level groups of smaller groups of shapes to complete the graphics to be displayed on screen.

Read the full book at www.amazon.com
Posted in Design Pattern, Design Pattern Interview Questions

Leave a Reply

Your email address will not be published. Required fields are marked *