LOW-LEVEL DESIGN · BEHAVIORAL PATTERNS · BEHAVIORAL · 43 OF 48

Visitor Design Pattern in Java: Double Dispatch Explained

How the Visitor pattern adds new operations, like postage, labels and customs checks, to a fixed family of shipment classes without editing them: accept and visit methods, double dispatch step by step, the trade-off when a new type arrives, sealed interfaces and pattern matching as the modern Java alternative, and where Visitor shows up in LLD interviews.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 18

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 131 lines, with a small main() demo. Save it as ShipmentVisitorDemo.java, then run javac ShipmentVisitorDemo.java && java ShipmentVisitorDemo.

import java.util.List;

/** Visitor: add new operations over a fixed family of shipment types without editing those types. */
public class ShipmentVisitorDemo {

    // ---------- 1. The problem: one instanceof chain per operation ----------
    static long naivePostage(Object item) {
        if (item instanceof LetterItem l) {
            return 500 + (l.express() ? 300 : 0);
        } else if (item instanceof BoxItem b) {
            return 4000 + b.grams() / 100 * 50;
        }
        return 0; // ColdBox was forgotten, and nothing warned us
    }

    public static void main(String[] args) {
        List<Shipment> shipments = List.of(
                new LetterItem("L-1", true),
                new BoxItem("B-7", 1200),
                new ColdBox("C-3", 2500, 6));

        long naive = naivePostage(shipments.get(2));
        System.out.println("Naive postage for the chilled box: " + naive + " cents (bug!)");

        // ---------- 2. With visitors: each operation is one class ----------
        PostageCalculator postage = new PostageCalculator();
        LabelPrinter labels = new LabelPrinter();
        long total = 0;
        for (Shipment s : shipments) {
            long cents = s.accept(postage);       // double dispatch: accept, then visitXxx
            total += cents;
            System.out.println(s.accept(labels) + " -> " + cents + " cents");
        }
        System.out.println("Total postage: " + total + " cents");

        // ---------- 3. A new operation later: no element class changes ----------
        CustomsCheck customs = new CustomsCheck();
        for (Shipment s : shipments) {
            System.out.println("Customs declaration for " + s.accept(labels) + ": " + s.accept(customs));
        }
    }
}

// ---------- Elements: stable data types with one accept method each ----------
interface Shipment {
    <R> R accept(ShipmentVisitor<R> visitor);
}

record LetterItem(String id, boolean express) implements Shipment {
    @Override
    public <R> R accept(ShipmentVisitor<R> visitor) {
        return visitor.visitLetter(this);
    }
}

record BoxItem(String id, int grams) implements Shipment {
    @Override
    public <R> R accept(ShipmentVisitor<R> visitor) {
        return visitor.visitBox(this);
    }
}

record ColdBox(String id, int grams, int hoursCold) implements Shipment {
    @Override
    public <R> R accept(ShipmentVisitor<R> visitor) {
        return visitor.visitColdBox(this);
    }
}

// ---------- The visitor: one method per element type ----------
interface ShipmentVisitor<R> {
    R visitLetter(LetterItem letter);

    R visitBox(BoxItem box);

    R visitColdBox(ColdBox box);
}

/** Operation 1: all postage rules in one place. Forgetting a type is a compile error. */
class PostageCalculator implements ShipmentVisitor<Long> {
    @Override
    public Long visitLetter(LetterItem letter) {
        return 500L + (letter.express() ? 300 : 0);
    }

    @Override
    public Long visitBox(BoxItem box) {
        return 4000L + box.grams() / 100 * 50L;
    }

    @Override
    public Long visitColdBox(ColdBox box) {
        return 6000L + box.grams() / 100 * 80L + box.hoursCold() * 100L;
    }
}

/** Operation 2: label text. Returns a different type thanks to the generic visitor. */
class LabelPrinter implements ShipmentVisitor<String> {
    @Override
    public String visitLetter(LetterItem letter) {
        return "[LETTER " + letter.id() + (letter.express() ? " EXPRESS]" : "]");
    }

    @Override
    public String visitBox(BoxItem box) {
        return "[BOX " + box.id() + " " + box.grams() + "g]";
    }

    @Override
    public String visitColdBox(ColdBox box) {
        return "[KEEP COLD " + box.id() + " " + box.hoursCold() + "h]";
    }
}

/** Operation 3, added later as a new file: does this shipment need a customs declaration? */
class CustomsCheck implements ShipmentVisitor<Boolean> {
    @Override
    public Boolean visitLetter(LetterItem letter) {
        return false;
    }

    @Override
    public Boolean visitBox(BoxItem box) {
        return box.grams() > 2000;
    }

    @Override
    public Boolean visitColdBox(ColdBox box) {
        return true; // food always needs a declaration
    }
}

Notes

The problem

Here is the first attempt. A postage method takes any item and runs a chain of instance of checks. It works for letters and boxes. But someone forgot the chilled box, so it silently costs zero. Now copy this chain for labels, for customs and for reports. Each copy can miss a type, and nothing warns you. The bug only shows up when a customer ships ice cream for free.

The other option is to put each operation inside the classes: a postage method, a label method and a customs method on all three. Now the type checks are gone, but the shipment classes keep growing with code that is not really theirs. Printing and tax rules sit next to the data. Every new report means editing, retesting and redeploying all three classes. Neither option scales.

Naive postage
long postage(Object item) {
  if (item instanceof LetterItem l)
    return 500 + (l.express() ? 300 : 0);
  else if (item instanceof BoxItem b)
    return 4000 + b.grams() / 100 * 50;
  return 0; // ColdBox forgotten!
}

The idea

The idea in one sentence: move each operation out of the element classes and into its own visitor class, which has one visit method per element type. The elements learn just one small trick, an accept method that hands themselves to the visitor. Formally, Visitor represents an operation over a group of related types, so you can add new operations without changing those types.

Visitor in one line
  • move each operation out of
  • the classes, into a visitor
  • class with one visit method
  • per element type
  • elements only learn one
  • trick: accept(visitor)

Structure

Here is the full picture. On the left, the Shipment interface and its three element classes. On the right, the ShipmentVisitor interface and the operations: PostageCalculator, LabelPrinter, and later CustomsCheck. The Dispatcher holds a list of shipments and a visitor, and simply asks each shipment to accept the visitor. It never checks types itself.

Code: elements

The element side is tiny. The Shipment interface has a single generic accept method that takes a visitor and returns whatever that visitor produces. Each element implements it in one line: the box calls visit box and passes itself. The letter calls visit letter, the cold box calls visit cold box. The elements stay as plain data records. They do not know what postage or labels are.

Elements
interface Shipment {
  <R> R accept(ShipmentVisitor<R> v);
}
record BoxItem(String id, int grams)
    implements Shipment {
  public <R> R accept(
      ShipmentVisitor<R> v) {
    return v.visitBox(this);
  }
}

Code: visitor

The visitor interface lists one visit method for every element type. Making it generic is a neat Java touch: the postage calculator returns a Long number of cents, and the label printer returns a String. No casting, no shared result field. If you prefer, visitors can also keep state, like a running total, and return nothing.

The visitor interface
interface ShipmentVisitor<R> {
  R visitLetter(LetterItem letter);
  R visitBox(BoxItem box);
  R visitColdBox(ColdBox box);
}

PostageCalculator
  implements ShipmentVisitor<Long>
LabelPrinter
  implements ShipmentVisitor<String>

Code: one operation

Now every postage rule lives in one class. Letters cost five hundred cents plus a fee for express. Boxes pay by weight. Chilled boxes pay by weight plus a charge for each hour of cooling. If the pricing team changes a rate, you open exactly one file. And because the interface demands a visit cold box method, you cannot forget the chilled box: the code will not compile.

PostageCalculator
public Long visitLetter(LetterItem l) {
  return 500L + (l.express() ? 300 : 0);
}
public Long visitBox(BoxItem b) {
  return 4000L + b.grams() / 100 * 50L;
}
public Long visitColdBox(ColdBox c) {
  return 6000L + c.grams() / 100 * 80L
      + c.hoursCold() * 100L;
}

Double dispatch

Watch one call. The dispatcher holds the box only as a Shipment, so it calls accept with the postage visitor. Java picks the box's accept at runtime. That is the first dispatch. Inside, the box calls visit box on the visitor, and Java picks the postage version at runtime. That is the second dispatch. Two virtual calls together choose the code by both the element type and the operation. This is called double dispatch.

Why the extra hop? Java chooses between overloaded methods by the declared type, at compile time, not by the real object. If a variable is declared as Shipment, the compiler cannot pick visit box for it. Calling accept on the object first lets normal runtime dispatch find the real class, and inside that class this has the exact type. That one line is the whole trick.

Why not just overload?
  • visit(LetterItem) and
  • visit(BoxItem) as overloads
  • are picked by the STATIC
  • type at compile time
  • Shipment s = new BoxItem(..)
  • visit(s) finds no match
  • accept() turns the static
  • type into the real type

Adding an operation

Here is the payoff. The customs team wants to know which shipments need a declaration. Letters never do, boxes over two kilograms do, chilled food always does. You write a CustomsCheck class that implements the visitor and returns a Boolean. You do not touch LetterItem, BoxItem or ColdBox. Tested classes stay closed, and the new rule is reviewed on its own.

The trade-off

The cost is on the other side. If the business adds a fourth type, say a drone parcel, the visitor interface gets a new method and every visitor must implement it. The compiler will list every place you need to change, which is helpful, but it is still many files. So the rule is simple: use Visitor when the set of types is stable and the list of operations keeps growing. If it is the opposite, plain polymorphism is better.

Which side changes?
  • new operation:
  • one new visitor class
  • new element type:
  • new visit method in the
  • interface and in EVERY
  • visitor
  • pick Visitor when types are
  • stable and operations grow

When to use it

Use Visitor when the element types are stable, there are many unrelated operations, and you often walk a mixed list or a tree of them. Skip it when new types arrive often, when there is only one operation, which a normal method handles fine, or when visitors would need private fields the elements should keep hidden. Visitor also feels heavy to newcomers, so do not reach for it for two classes.

Use it / skip it
  • use it when:
  • • types are stable
  • • many unrelated operations
  • • you walk a tree or list of
  • mixed objects
  • skip it when:
  • • new types arrive often
  • • there is only one operation
  • • elements must hide fields

Modern Java

Modern Java offers another route. In Java seventeen you can declare Shipment as a sealed interface that permits only the three record types. From Java twenty one, a switch with type patterns over a sealed type is checked for exhaustiveness, so a missing case fails to compile, with no accept methods at all. Many teams now prefer that for data records. On Java seventeen, the classic visitor is still the safe way to get that check.

Sealed alternative
  • Java 17: sealed interface
  • Shipment permits LetterItem,
  • BoxItem, ColdBox
  • Java 21: a switch with type
  • patterns over a sealed type
  • is checked for missing
  • cases, with no accept()
  • same goal: no forgotten type

Where you see it

You have used visitors already. The Java annotation processing API has an Element interface with an accept method that takes an ElementVisitor, exactly this pattern. Files dot walk file tree calls a FileVisitor for each folder and file, a looser callback style of the same idea. And almost every compiler, linter and code formatter walks its syntax tree with visitors.

In real code
  • javax.lang.model:
  • Element.accept(ElementVisitor)
  • used by annotation processors
  • java.nio.file.FileVisitor:
  • callbacks per file and
  • folder in Files.walkFileTree
  • compilers and linters walk
  • syntax trees with visitors

Related patterns

Do not confuse it with Strategy. A strategy is one swappable algorithm for one context. A visitor is one operation spread across many element types. Visitor pairs naturally with Composite: the composite builds a tree, like folders and files, and visitors compute size or search it. And compared with Iterator, the iterator decides how you move through items, while the visitor decides what you do at each one.

How it differs
  • Strategy: one interchangeable
  • algorithm for one context
  • Visitor: one operation spread
  • over MANY element types
  • Composite: the tree that a
  • visitor often walks
  • Iterator: how you move;
  • Visitor: what you do

In LLD interviews

In interviews, Visitor fits when a stable hierarchy needs many calculations. A file system design where you compute total size, search and permissions over files and folders. A cart where tax rules differ by item type. An expression tree you evaluate, print and simplify. The common mistake is using it on a hierarchy that changes every sprint. Say the trade-off out loud and the interviewer will trust the choice.

Where it fits
  • file system: size, search,
  • permissions over files
  • and folders
  • shopping cart: tax and
  • discount per item type
  • expression tree: evaluate,
  • print, simplify
  • mistake: Visitor for a
  • hierarchy that keeps growing

Interview questions

What problem does the Visitor pattern solve?

It lets you add new operations over a fixed set of classes without changing those classes. Each operation becomes its own visitor class with one method per element type, so related logic stays together and the element classes stay small.

What is double dispatch?

Choosing which code runs based on the runtime types of two objects. In Visitor, element.accept(visitor) dispatches on the element type, and inside it visitor.visitX(this) dispatches on the visitor type, so the pair decides the method.

Why can Java not just use overloaded visit methods without accept?

Java resolves overloads at compile time using the declared type of the argument. A variable typed as the base interface cannot select the subtype overload, so accept() is needed to reach the real class first.

What is the main downside of Visitor?

Adding a new element type forces a new method on the visitor interface and a change in every visitor class. It also adds indirection that can confuse readers and may push elements to expose fields so visitors can read them.

When would you choose Visitor over plain polymorphism?

When the element types are stable and the number of operations keeps growing, especially operations unrelated to the elements core job, such as reports, exports or pricing. If new types arrive often, put methods on the types instead.

How do sealed interfaces relate to Visitor?

A sealed interface fixes the list of permitted subtypes. From Java 21, a switch with type patterns over a sealed type is checked for missing cases, which gives Visitor-like safety without accept methods. In Java 17 you can seal the type but switch patterns are not final yet.

Can a visitor keep state?

Yes. A visitor can accumulate a running total, collect errors or track depth while walking a tree. That state belongs to one traversal, so create a fresh visitor per run or reset it, and do not share a stateful visitor across threads.

Where is Visitor used in the Java ecosystem?

The annotation processing API uses Element.accept(ElementVisitor). Files.walkFileTree takes a FileVisitor with callbacks for files and directories. Compilers, linters and template engines commonly walk syntax trees with visitors.