Browse Java Design Patterns & Enterprise Application Architecture

Implementing Visitor in Java

Implement Visitor in Java when the object structure is stable and the system needs multiple separate operations over it.

On this page

Visitor: A pattern that moves operations out of element classes and into visitor types, usually when many operations must traverse a stable object structure.

A minimal Java visitor shape looks like this:

1public interface DocumentVisitor {
2    void visitParagraph(Paragraph paragraph);
3    void visitImage(ImageNode image);
4}

Each element accepts the visitor:

 1public interface DocumentNode {
 2    void accept(DocumentVisitor visitor);
 3}
 4
 5public final class Paragraph implements DocumentNode {
 6    @Override
 7    public void accept(DocumentVisitor visitor) {
 8        visitor.visitParagraph(this);
 9    }
10}

Why It Helps

Visitor works when the object structure is stable enough that adding a new operation is more common than adding a new element type.

Why It Hurts

If new element types appear often, every visitor must change. That is the main trade-off.

Revised on Thursday, April 23, 2026