39 lines
1.2 KiB
Java
39 lines
1.2 KiB
Java
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 ===");
|
|
}
|
|
}
|