Composite Design Pattern
The Composite Design Pattern is a structural design pattern that allows you to compose objects into tree structures to represent part-whole hierarchies. It lets clients treat individual objects and compositions of objects uniformly.
🔶 Motivation
Imagine you are designing a file system:
You want to be able to perform operations like getSize() on both files and directories, and treat them the same way in your code. This is where the Composite Pattern is helpful.
🔧 Structure
Participants:
UML Diagram:
🧾 Example in Java-like Pseudocode
Usage:
✅ Advantages
❌ Disadvantages
📌 Real-World Use Cases
🧠 Best Practices
✅ Use the Composite Pattern when:
1. You have a part-whole hierarchy
2. You want to treat individual and composite objects uniformly
✅ "A File and a Folder both support getSize(), so the client can just call getSize() on any FileSystemItem without knowing what it really is."
3. You need to perform operations recursively over a tree structure
4. You want to simplify client code
❌ Avoid Composite Pattern when:
✘ The tree structure is not needed.
✘ You need different interfaces for leaf and composite.