Implement Visitor in Java when the object structure is stable and the system needs multiple separate operations over it.
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}
Visitor works when the object structure is stable enough that adding a new operation is more common than adding a new element type.
If new element types appear often, every visitor must change. That is the main trade-off.