Java Omnibus
OOAD & Architecture / GoF patterns / Behavioral / Visitor Pattern in Java
GoF Behavioral Java Order Management
GoF Pattern

Visitor helps when you have a stable object structure but need to add multiple new operations across it cleanly.

Represent an operation to be performed on elements of an object structure, letting you define new operations without changing the element classes.

Intent

What the pattern is trying to do

Represent an operation to be performed on elements of an object structure, letting you define new operations without changing the element classes.

Problem

What force creates the need

You need new operations across an existing object structure, but changing every element class repeatedly would be painful.

Solution

How the pattern responds

Separate operations into visitor objects while element classes accept visitors through a stable protocol.

Structure

How the moving parts fit together

Elements expose an accept method, and visitors implement type-specific operations for each element kind.

Java Example

Java example in the Order Management domain

Visitor Pattern in Java example
package org.javaomnibus.ecommerce.gof.behavioral;

public interface OrderNode {
    void accept(OrderNodeVisitor visitor);
}

public interface OrderNodeVisitor {
    void visit(ProductOrderNode node);
}

public final class ProductOrderNode implements OrderNode {
    @Override
    public void accept(OrderNodeVisitor visitor) {
        visitor.visit(this);
    }
}
Code Walkthrough

Step by step

  1. The object structure stays stable while new operations move into visitors.
  2. Visitors are useful when many cross-cutting operations target the same structure.
  3. This pattern is most justified when element types are stable but operations keep growing.
  4. Visitor is more specialized than many other GoF patterns and should be applied deliberately.
When To Use

Where this pattern helps

  • When you have a stable structure and many operations over it
  • When adding operations without editing element classes repeatedly matters
When Not To Use

When a simpler design is better

  • When the element hierarchy changes often
  • When the added complexity outweighs the benefit of externalized operations
Trade-Offs

What this pattern costs

  • Adding a new element type can force updates across all visitors
  • The pattern can feel heavy in ordinary business code
Modern Relevance

How this fits today

Visitor still matters in compilers, AST processing, reporting pipelines, and rule/tree processing, though many Java applications do not need it daily.

Common Misuse

Where teams get it wrong

Applying Visitor to unstable domain models usually creates more maintenance burden than design benefit.

Related Patterns

Compare with nearby choices


What To Read Next