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
- 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:
- https://stackoverflow.com/questions/5334353/when-should-i-use-composite-design-pattern/31449846#31449846
- https://sourcemaking.com/design_patterns/composite/java/1
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 😄