Composite Design Pattern The Problem What is it? How it works?

Composite Design Pattern


The Problem:

Lets say you've been tasked with creating a file explorer system as part of a larger group project. On top of being able to store and organize various files types, the system needs way to calculate the sizes of all of its folder & files within the folder. And because of the nature of group work, you don't have all the implementation details of the file classes that'll be store inside each folders. Do the different file objects even have a way to track file size? How can we get the size info? Do we have to call a method or do we have to manually access the attribute of the class?


What is Composite Design Pattern?

The Composite Design Pattern is way of structuring your code so that certain big objects (composites) will contain other 'smaller' objects (leafs or parts) usually resulting in a tree-like hierarchy structure.

Key characteristic:

How does it work?

1. Ensure that all classes/objects share an similar / same interface. This means that all leaf and composite components must have certain methods that the programmer interact with. ( in the diagram below both leaf and component share the same execute method )


2. The leaf components of the structure should do most of the work. In the context of the file explorer, it means the files must have some sort of method to calculate the file size and return it. The folders themselves simply calls the getSize() method of all its children.


3.The composite object will have a way to store all the children components, and methods to interact with them.But they don't necessary know about the children's implementation detail.