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

shapes/Shape.java: Common shape interface

package refactoring_guru.visitor.example.shapes;

import refactoring_guru.visitor.example.visitor.Visitor;

public interface Shape {
    void move(int x, int y);
    void draw();
    String accept(Visitor visitor);
}

shapes/Dot.java: A dot

shapes/Circle.java: A circle

shapes/Rectangle.java: A rectangle

shapes/CompoundShape.java: A compound shape

visitor

visitor/Visitor.java: Common visitor interface

visitor/XMLExportVisitor.java: Concrete visitor, exports all shapes into XML

Demo.java: Client code

OutputDemo.txt: Execution result

Last updated