Composite Pattern in Java

Arjun Sunil Kumar
Software Engineering
2 min readAug 18, 2018

When hierarchy matters !

Use case:

Files, Folders and Everything Nice 😸 ! #PPG

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 😄

--

--

Arjun Sunil Kumar
Software Engineering

Writes on Database Kernel, Distributed Systems, Cloud Technology, Data Engineering & SDE Paradigm. github.com/arjunsk