The composite design pattern is about a hierarchy where nodes with children have different behavior than childless nodes.
The pattern consists of three elements:
- Component : a super-class typically an interface
- Composite : a node with children implements Component
- Leaf : a childless node implements Component
A typical example is a file system where there are folders and files:
Folders can contain files , other folders or can be empty. On the other hand files don’t contain folders or other files!
Remember , the most important aspect of a design pattern is it’s intent! Once you understand it, you can use the pattern effectively in your projects!
Here you will explore a simple file system , where you can see a simple implementation of the pattern.
Here you can see a UML of our File System :
Take a moment to explore the code and:
- note what component of the pattern each class represents
- observe the output of the code and see the difference between a file and a folder
- in what scenarios do you think this pattern would be useful?
Time to get your hands dirty:
Now that you understand how the composite pattern works , lets extend our FileSystem by adding new file types!
Take the code and implement a new File type: Img
- The Img should implement FileComponent
- Img must have a data field, you can use anything you like
- You can use the display method of the file to customize it for the new file
- Create an Img object and add it to a folder!
By the end of this project you have applied the pattern in an existing code-base and gained practical experience applying it.
Happy coding !!!