Files

54 lines
1.5 KiB
Java

package composite;
import java.util.ArrayList;
import java.util.List;
/**
* Composite — a directory that can hold both Files (leaves)
* and other Directories (composites).
*
* getSize() is recursive: it asks each child for its size and sums them.
* The caller doesn't care whether a child is a File or Directory —
* both implement FileSystemItem and answer getSize().
*
* This is the power of Composite: uniform treatment of simple and complex.
*/
public class Directory implements FileSystemItem {
private final String name;
private final List<FileSystemItem> children = new ArrayList<>();
public Directory(String name) {
this.name = name;
}
public Directory add(FileSystemItem item) {
children.add(item);
return this; // fluent API for easy nesting
}
public void remove(FileSystemItem item) {
children.remove(item);
}
@Override
public String getName() { return name; }
@Override
public long getSize() {
// Recursion: each child knows its own size.
// Files return their bytes; directories sum their children.
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 + " "); // recurse with deeper indent
}
}
}