Part 2 of 6 · 3 min read
Composite
One interface for a leaf and a group.
Think of an army. A soldier can be given an order. So can a squad, a company or the whole army. The same order, such as "march", goes to any of them, and a group passes it on to its members. The commander does not care whether the unit is one soldier or ten thousand.
GoF's applicability for Composite is two cases: you want to represent part-whole hierarchies, and you want clients to ignore the difference between a single object and a group of objects, treating all of them in the same way. The idea is a common interface for the single objects, called leaves, and for the groups, called composites. A composite holds children that follow the same interface, and forwards requests to them.
A file system fits. A file has a size. A folder has a size too, which is the sum of the sizes of what it holds, and a folder can hold folders.
interface Node {
String name();
long size();
void print(StringBuilder sb, int depth);
}
class FileNode implements Node {
private final String name; private final long size;
FileNode(String n, long s) { name = n; size = s; }
public String name() { return name; }
public long size() { return size; }
public void print(StringBuilder sb, int d) {
sb.append(" ".repeat(d)).append(name).append(" (").append(size).append(")\n");
}
}
class Folder implements Node {
private final String name; private final List<Node> children = new ArrayList<>();
Folder(String n) { name = n; }
Folder add(Node n) { children.add(n); return this; }
public String name() { return name; }
public long size() { long t = 0; for (Node c : children) t += c.size(); return t; }
public void print(StringBuilder sb, int d) {
sb.append(" ".repeat(d)).append(name).append("/\n");
for (Node c : children) c.print(sb, d + 1);
}
}
Build a root folder holding a.txt (size 10, made up), a docs folder with b.md (5) and c.md (7), and an empty folder. The root's size is 22, and the docs size is 12. The empty folder has size 0 and needs no special case. The printed tree shows each name indented by its depth.
The client calls root.size() with no thought for what is inside. This is what GoF means by making the client simple: it need not write case statements to tell files from folders. New kinds of node, such as a shortcut, work with the existing code at once.
GoF also lists a liability. The design can become overly general. It is hard to restrict which components a composite may hold, because the type system does not stop you putting any Node in any folder. Rules such as "a menu may hold only items and submenus" must be checked at run time.
Composite pattern
The Composite pattern gives single objects and groups of objects the same interface, so a group can hold other groups and clients treat them alike.
Example: FileNode and Folder, both Node.
Check yourself:
1. What are the sizes of the root and of docs in the example?
2. Why does the client not need a case statement?
3. What is the liability GoF names?