Add all 23 GoF design pattern implementations (2026-06-13)
This commit is contained in:
38
03-behavioral/visitor/Main.java
Normal file
38
03-behavioral/visitor/Main.java
Normal file
@@ -0,0 +1,38 @@
|
||||
package visitor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Visitor Design Pattern — Runnable Demo
|
||||
* Run: javac visitor/*.java -d out/visitor && java -cp out/visitor visitor.Main
|
||||
* Article: https://ankurm.com/visitor-design-pattern-java/
|
||||
*/
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
System.out.println("=== Visitor Design Pattern Demo ===\n");
|
||||
|
||||
List<Shape> shapes = List.of(
|
||||
new Circle(5),
|
||||
new Rectangle(4, 6),
|
||||
new Triangle(3, 8)
|
||||
);
|
||||
|
||||
System.out.println("-- Area Calculator Visitor --");
|
||||
ShapeVisitor areaCalc = new AreaCalculator();
|
||||
for (Shape shape : shapes) {
|
||||
shape.accept(areaCalc);
|
||||
}
|
||||
|
||||
System.out.println("\n-- Perimeter Calculator Visitor --");
|
||||
ShapeVisitor perimCalc = new PerimeterCalculator();
|
||||
for (Shape shape : shapes) {
|
||||
shape.accept(perimCalc);
|
||||
}
|
||||
|
||||
System.out.println("\n-- Key insight --");
|
||||
System.out.println("Added PerimeterCalculator without touching Shape, Circle, Rectangle, Triangle.");
|
||||
System.out.println("To add another operation: write one new Visitor class.");
|
||||
|
||||
System.out.println("\n=== Demo complete ===");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user