package composite; import java.util.ArrayList; import java.util.List; /** * Composite — a directory that holds both Files (leaves) and other Directories. * * getSize() is recursive: asks each child for its size and sums them. * print() recurses with deeper indentation. * * The caller doesn't care whether a child is a File or Directory — * both answer getSize() and print() the same way. */ public class Directory implements FileSystemItem { private final String name; private final List children = new ArrayList<>(); public Directory(String name) { this.name = name; } // Fluent add() — allows chaining: dir.add(file1).add(file2).add(subDir) public Directory add(FileSystemItem item) { children.add(item); return this; } public void remove(FileSystemItem item) { children.remove(item); } @Override public String getName() { return name; } @Override public long getSize() { // Each child knows its own size: files return bytes, directories recurse. // This is the Composite's core: uniform delegation down the tree. return children.stream() .mapToLong(FileSystemItem::getSize) .sum(); } @Override public void print(String indent) { System.out.printf("%s[DIR] %s/ (%,d bytes total)%n", indent, name, getSize()); for (FileSystemItem child : children) { child.print(indent + " "); // each level indents 4 more spaces } } }