Composite Pattern in Java

When hierarchy matters !

Use case:

When you are developing a File Manager. You have two kind of list items: Files & Folders. So we have doubleClick() action for both Files & Folders. Files have different implementation when compared to Folders. And also, a Folder can contain 0…N File/Folders. So this is having a tree hierarchy. In this case, we create Interface for ListItem, and then create concrete classes for Files and Folders implementing the ListItem interface.

File Manage Example:

Say, we need to implement the tree above. The Nodes are either Folders or Files.

Project Structure:

Implementation in Java

  1. Lets create the Node Interface. As of now, we are including only doubleClick(). Ideally it could have displayProperty(), getSize() etc.

IData.java

2. Create concretions of the above. Variants of Node : File & Folder.

FolderData.java

FileData.java

3. Driver for testing the above.

Found it Interesting?
Please show your support by 👏. To read the complete series, click below.

Reference:

Disclaimer:
I myself, has just started learning, design patterns. If you find any issues please feel free to post them in the comments section below. Thank you for reading so far 😄

Writes on Big Data, AWS & Backend technologies.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store