Dezign Patterns
Composite Design Pattern
The Composite Pattern allows you to compose objects into tree-like structures to represent part-whole hierarchies. It lets clients treat individual objects and composites of objects uniformly.
Intent
The Composite pattern is used to treat individual objects and compositions of objects uniformly. It lets you build tree structures of objects where leaf nodes and composite nodes (containers) can be treated the same.
Participents
- Component : Defines the common interface [FileSystemItem]
- Leaf : Implements behavior for leaf elements [File]
- Composite : Manages child components [Folder]
// Component
interface FileSystemItem {
void display(String indent);
}
// Leaf
class File implements FileSystemItem {
private String name;
public File(String name) {
this.name = name;
}
public void display(String indent) {
System.out.println(indent + "- File: " + name);
}
}
// Composite
class Folder implements FileSystemItem {
private String name;
private List<FileSystemItem> items = new ArrayList<>();
public Folder(String name) {
this.name = name;
}
public void add(FileSystemItem item) {
items.add(item);
}
public void display(String indent) {
System.out.println(indent + "+ Folder: " + name);
for (FileSystemItem item : items) {
item.display(indent + " ");
}
}
}
//Client code
public class Main {
public static void main(String[] args) {
File file1 = new File("resume.pdf");
File file2 = new File("coverletter.docx");
Folder folder1 = new Folder("Job Applications");
folder1.add(file1);
folder1.add(file2);
File file3 = new File("photo.png");
Folder root = new Folder("My Documents");
root.add(folder1);
root.add(file3);
root.display("");
}
}
//Output
+ Folder: My Documents
+ Folder: Job Applications
- File: resume.pdf
- File: coverletter.docx
- File: photo.png