Composite Design Pattern in Java
Composite lets you treat one object and a group of objects in the same way. Objects are arranged like a tree.
Real life example
A folder can hold files and other folders. You can ask any of them for its size.
When to use
Your data is a tree (parts inside parts) and you want one simple way to work with all of it.
Complete Java example
Save this as Main.java, then run javac Main.java and java Main.
import java.util.*;
public class Main {
public static void main(String[] args) {
Folder root = new Folder();
root.add(new File(10));
Folder sub = new Folder();
sub.add(new File(5));
root.add(sub);
System.out.println(root.size()); // 15
}
}
interface Item { int size(); }
class File implements Item {
private int size;
File(int size) { this.size = size; }
public int size() { return size; }
}
class Folder implements Item {
private List<Item> items = new ArrayList<>();
void add(Item i) { items.add(i); }
public int size() {
int total = 0;
for (Item i : items) total += i.size(); // works for files and folders
return total;
}
}Output
15