Visitor in Java
Visitor is a behavioral design pattern that allows adding new behaviors to existing class hierarchy without altering any existing code.
Read why Visitors can’t be simply replaced with method overloading in our article Visitor and Double Dispatch.
Usage of the pattern in Java
Usage examples: Visitor isn’t a very common pattern because of its complexity and narrow applicability.
Here are some examples of pattern in core Java libraries:
Exporting shapes into XML
In this example, we would want to export a set of geometric shapes into XML. The catch is that we don’t want to change the code of shapes directly or at least keep it to the minimum.
In the end, the Visitor pattern establishes an infrastructure that allows us to add any behaviors to the shapes hierarchy without changing the existing code of those classes.
shapes/Shape.java: Common shape interface
shapes/Dot.java: A dot
shapes/Circle.java: A circle
shapes/Rectangle.java: A rectangle
shapes/CompoundShape.java: A compound shape
visitor/Visitor.java: Common visitor interface
visitor/XMLExportVisitor.java: Concrete visitor, exports all shapes into XML
Demo.java: Client code
OutputDemo.txt: Execution result