Add all 23 GoF design pattern implementations (2026-06-13)
This commit is contained in:
58
02-structural/composite/Main.java
Normal file
58
02-structural/composite/Main.java
Normal file
@@ -0,0 +1,58 @@
|
||||
package composite;
|
||||
|
||||
/**
|
||||
* Composite Design Pattern — Runnable Demo
|
||||
*
|
||||
* Builds a file system tree with nested directories and files.
|
||||
* Demonstrates that getSize() and print() work uniformly on
|
||||
* leaves (File) and composites (Directory) without any instanceof checks.
|
||||
*
|
||||
* Run: javac composite/*.java && java composite.Main
|
||||
* Article: https://ankurm.com/composite-design-pattern-java/
|
||||
*/
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println("=== Composite Design Pattern Demo ===\n");
|
||||
|
||||
// Build a file system tree
|
||||
Directory root = new Directory("project");
|
||||
|
||||
Directory src = new Directory("src");
|
||||
Directory main = new Directory("main");
|
||||
main.add(new File("App.java", 4_200))
|
||||
.add(new File("Config.java", 1_800))
|
||||
.add(new File("Application.yml", 3_100));
|
||||
|
||||
Directory test = new Directory("test");
|
||||
test.add(new File("AppTest.java", 2_600))
|
||||
.add(new File("ConfigTest.java", 1_200));
|
||||
|
||||
src.add(main).add(test);
|
||||
|
||||
Directory resources = new Directory("resources");
|
||||
resources.add(new File("application.yml", 1_500))
|
||||
.add(new File("logback.xml", 900))
|
||||
.add(new File("banner.txt", 200));
|
||||
|
||||
root.add(src)
|
||||
.add(resources)
|
||||
.add(new File("pom.xml", 8_400))
|
||||
.add(new File("README.md", 2_100));
|
||||
|
||||
// Print entire tree — recursion happens automatically
|
||||
System.out.println("File system tree:");
|
||||
root.print("");
|
||||
|
||||
System.out.printf("%nTotal project size: %,d bytes%n", root.getSize());
|
||||
|
||||
// Client treats File and Directory identically
|
||||
System.out.println("\n-- Treating File and Directory uniformly --");
|
||||
FileSystemItem[] items = { new File("standalone.txt", 500), src };
|
||||
for (FileSystemItem item : items) {
|
||||
System.out.printf("%s -> size: %,d bytes%n", item.getName(), item.getSize());
|
||||
}
|
||||
|
||||
System.out.println("\n=== Demo complete ===");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user