1.8 KiB
Visitor Design Pattern — Java Example
Pattern: Behavioral → Visitor Article: https://ankurm.com/visitor-design-pattern-java/
What this example shows
A shape hierarchy that never changes, with operations added as separate visitor classes instead of methods on each shape. ShapeVisitor declares one visit() overload per concrete type. Shape declares accept(ShapeVisitor) — the double-dispatch trick: the shape hands itself to the visitor as a concretely-typed this, so overload resolution picks the right visit() method with no instanceof checks anywhere. Circle, Rectangle, and Triangle are plain data holders that know nothing about area or perimeter. AreaCalculator and PerimeterCalculator are two concrete visitors — adding the second one required zero changes to any shape class. Main runs both visitors across the same three shapes.
How to run
javac visitor/*.java -d out/visitor
java -cp out/visitor visitor.Main
Requires Java 25.
Post Section ↔ File Mapping
| Post Section | File(s) |
|---|---|
| Implementation: Shape Geometry Operations — the Visitor interface | ShapeVisitor.java |
| Implementation: Shape Geometry Operations — the Element interface | Shape.java |
| Implementation: Shape Geometry Operations — Circle | Circle.java |
| Implementation: Shape Geometry Operations — Rectangle | Rectangle.java |
| Implementation: Shape Geometry Operations — Triangle | Triangle.java |
| Implementation: Shape Geometry Operations — AreaCalculator | AreaCalculator.java |
| Implementation: Shape Geometry Operations — PerimeterCalculator | PerimeterCalculator.java |
| Implementation: Shape Geometry Operations — wiring it together | Main.java |
Article: https://ankurm.com/visitor-design-pattern-java/ All patterns: https://ankurm.com/design-patterns-java/