Sync Composite to Java 25: H6 file labels, fix console output typo, README mapping
This commit is contained in:
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user