Sync Composite to Java 25: H6 file labels, fix console output typo, README mapping

This commit is contained in:
2026-06-24 14:30:27 +05:30
parent 4091345b20
commit ad6a65a95d
6 changed files with 77 additions and 76 deletions

View File

@@ -1,53 +1,39 @@
package composite;
import java.util.ArrayList;
import java.util.List;
/**
* Composite — a directory that can hold both Files (leaves)
* and other Directories (composites).
* 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.
*
* 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.
* both answer getSize() and print() the same way.
*/
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(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; // fluent API for easy nesting
return this;
}
public void remove(FileSystemItem item) {
children.remove(item);
}
@Override
public String getName() { return name; }
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.
// 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 + " "); // recurse with deeper indent
child.print(indent + " "); // each level indents 4 more spaces
}
}
}