loading...
Cover image for Design Patterns — Composite

Design Patterns — Composite

achimoraites profile image Achilles Moraites ・2 min read

This has been posted on Medium

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

Alt Text

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!

Project : FileSystem

get the source code here

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 :

Alt Text

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?

Project : Extending our FileSystem

get the source code here

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

General Guidelines:

  • 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.

See the solution

Happy coding !!!

Discussion

pic
Editor guide