The Composite Design Pattern is a structural design pattern used to represent part-whole hierarchies. It allows you to treat individual objects and groups of objects uniformly.
In simple words:
π It lets you build tree-like structures where leaf nodes and composite nodes are handled in the same way.
π Why do we need Composite Pattern?
Imagine you are designing a file explorer like Windows Explorer:
-
A file is a simple object.
-
A folder is a complex object containing files and other folders.
But you still want to perform common operations like:
-
open
-
delete
-
show details
Without worrying whether it's a file or folder.
Composite pattern helps you treat both the same way.
π Structure of Composite Pattern

1. Component (interface or abstract class)
Defines common operations for both leaf & composite.
2. Leaf
Represents the basic object (no children).
3. Composite
Contains leaf or composite children and implements child-related operations.
π Real-Life Examples
| Example | Leaf | Composite |
|---|---|---|
| File System | File | Folder |
| Company Structure | Employee | Manager with team |
| UI Components | Button/Textbox | Panel with child components |
π Java Example (Simple and Clean)
// Component
interface Employee {
void showDetails();
}
// Leaf
class Developer implements Employee {
private String name;
public Developer(String name) {
this.name = name;
}
@Override
public void showDetails() {
System.out.println("Developer: " + name);
}
}
// Composite
class Manager implements Employee {
private String name;
private List<Employee> team = new ArrayList<>();
public Manager(String name) {
this.name = name;
}
public void add(Employee emp) {
team.add(emp);
}
public void remove(Employee emp) {
team.remove(emp);
}
@Override
public void showDetails() {
System.out.println("Manager: " + name);
for (Employee e : team) {
e.showDetails();
}
}
}
// Client
public class CompositeDemo {
public static void main(String[] args) {
Developer dev1 = new Developer("Amit");
Developer dev2 = new Developer("Riya");
Manager mgr = new Manager("Karan");
mgr.add(dev1);
mgr.add(dev2);
mgr.showDetails();
}
}
Output
Manager: Karan
Developer: Amit
Developer: Riya
π When to Use Composite Pattern
Use it when:
-
Your model forms a tree structure.
-
You want to treat single and grouped objects the same way.
-
You want uniform operations across all elements.
π Interview One-Liner Answer
Composite Pattern allows you to treat individual objects and compositions of objects uniformly by representing them as a tree structure.
No comments:
Post a Comment