Design patterns
patterns8CompositePattern
- Path
- pkg8patterns/patterns8CompositePattern.java
- Package
- pkg8patterns
- Study order
- 8
- Run
- Single-file source launch
- Command
- java pkg8patterns/patterns8CompositePattern.java
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg8patterns;2 3/*4 * Composite (Structural)5 * ----------------------6 * INTENT: compose objects into tree structures and treat individual objects and7 * compositions uniformly.8 * UML: Component <|-- Leaf and <|-- Composite (Composite holds Component children).9 * PROS: uniform treatment of leaves and groups; easy recursive operations.10 * CONS: can make the design overly general.11 * REAL-WORLD: file systems, UI component trees, org charts.12 */13import java.util.*;14 15public class patterns8CompositePattern {16 17 interface FileSystemNode { int size(); String name(); }18 19 // Leaf20 static class FileLeaf implements FileSystemNode {21 private final String name; private final int size;22 FileLeaf(String name, int size) { this.name = name; this.size = size; }23 public int size() { return size; }24 public String name() { return name; }25 }26 27 // Composite28 static class Directory implements FileSystemNode {29 private final String name;30 private final List<FileSystemNode> children = new ArrayList<>();31 Directory(String name) { this.name = name; }32 Directory add(FileSystemNode n) { children.add(n); return this; }33 public int size() { return children.stream().mapToInt(FileSystemNode::size).sum(); }34 public String name() { return name; }35 }36 37 public static void main(String[] args) {38 Directory root = new Directory("root")39 .add(new FileLeaf("a.txt", 100))40 .add(new Directory("sub")41 .add(new FileLeaf("b.txt", 200))42 .add(new FileLeaf("c.txt", 300)));43 System.out.println("total size of '" + root.name() + "' = " + root.size() + " bytes");44 }45}