Add all 23 GoF design pattern implementations (2026-06-13)

This commit is contained in:
Ankur
2026-06-13 21:44:56 +05:30
commit a5beb61425
106 changed files with 2977 additions and 0 deletions

View File

@@ -0,0 +1,53 @@
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
}
}
}