SyntaxPilot
Courses/Low-Level Design/Lesson 43
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Low-Level Design · Lesson 43 of 90

Visitor pattern

Visitor patternvisitorelementaccept and visitdouble dispatchsingle dispatchadding operations without changing classesAST examplevisitor vs sealed types with pattern matchingcost of adding new element types

These are the notes for Low-Level Design (LLD) episode 43, the tenth behavioural pattern (patterns about how objects share work and talk to each other). The Visitor pattern lets you add a brand new operation (tax, a receipt, a report, an export) to a whole family of classes without editing those classes. We start with a census officer visiting different buildings, watch three obvious approaches fail in a billing app, discover why Java can't pick a method by an argument's real type (single dispatch), and invent double dispatch with accept and visit. Then we pay the pattern's price (a new element type breaks every visitor), use it on its classic home, an abstract syntax tree, and compare it with modern Java's sealed interfaces + switch pattern matching. Every program was actually run with javac Main.java && java -cp . Main (Java 21). Outputs are real.

1. The real-life idea: a census officer

A census is when the government counts every household. The officer visits homes, shops and offices; next month a different officer comes to read the electricity meters. Same buildings, a new job each time.

In a census In code
Home, shop, office: different kinds of building Elements: the classes being worked on (Dish, Drink, Delivery)
The census officer, who carries the job to every door The visitor: one object = one operation (TaxVisitor)
"Please come in": the building just opens the door accept(visitor): the element lets the visitor in
A different form for each building type visit(Dish), visit(Drink)...: one method per element type

2. The problem: operations keep coming

Asha's cafe bill holds three kinds of item: a Dish, a Drink and the Delivery fee. Each is a small record (episode 3: a compact class for plain data). The accountant wants GST (India's goods and services tax) on the bill. The rates in this demo (5% on food, 18% on drinks and delivery) are example numbers.

Obvious way 1: a method in every class. Fine for tax(). But then come receipt(), calories(), points(), toJson()... Every new operation edits every class. That breaks the Open-Closed Principle (episode 13: add behaviour without modifying working code), and the classes belong to the menu team, so Asha's team can't touch them anyway.

Obvious way 2: an instanceof chain outside the classes

import java.util.*;
interface Item { String name(); int price(); }
record Dish(String name, int price) implements Item { }
record Drink(String name, int price) implements Item { }
record Delivery(String name, int price) implements Item { }
record Tip(String name, int price) implements Item { }      // added later
public class Main {
    static double tax(Item it) {
        if (it instanceof Dish)  return it.price() * 0.05;
        if (it instanceof Drink) return it.price() * 0.18;
        if (it instanceof Delivery) return it.price() * 0.18;
        throw new IllegalArgumentException("unknown item: " + it);
    }
    public static void main(String[] args) {
        List<Item> bill = List.of(new Dish("Thali", 200), new Drink("Cola", 50),
                new Delivery("Delivery", 40), new Tip("Tip", 30));
        double total = 0;
        for (Item it : bill) total += tax(it);
        System.out.println("GST: " + total);
    }
}

Output (real):

Exception in thread "main" java.lang.IllegalArgumentException: unknown item: Tip[name=Tip, price=30]
    at Main.tax(Main.java:12)
    at Main.main(Main.java:18)

A new type (Tip) was added and nobody updated the chain. The compiler couldn't warn us; the bug appears at runtime, on a customer's bill. With ten operations there are ten chains to hunt down.

Obvious way 3: overloading

Overloading (episode 9) means several methods with the same name and different parameter types.

import java.util.*;
interface Item { String name(); int price(); }
record Dish(String name, int price) implements Item { }
record Drink(String name, int price) implements Item { }
record Delivery(String name, int price) implements Item { }
public class Main {
    static double tax(Dish d)     { return d.price() * 0.05; }   // food: 5%
    static double tax(Drink d)    { return d.price() * 0.18; }   // drinks: 18%
    static double tax(Delivery d) { return d.price() * 0.18; }   // fee: 18%
    public static void main(String[] args) {
        List<Item> bill = List.of(new Dish("Thali", 200),
                new Drink("Cola", 50), new Delivery("Delivery", 40));
        double total = 0;
        for (Item it : bill) total += tax(it);       // pick by type?
        System.out.println("GST: " + total);
    }
}

Output (real):

Main.java:14: error: no suitable method found for tax(Item)
        for (Item it : bill) total += tax(it);       // pick by type?
                                      ^
    method Main.tax(Dish) is not applicable
      (argument mismatch; Item cannot be converted to Dish)
    method Main.tax(Drink) is not applicable
      (argument mismatch; Item cannot be converted to Drink)
    method Main.tax(Delivery) is not applicable
      (argument mismatch; Item cannot be converted to Delivery)
1 error

3. Why it failed: single dispatch

  • The static type is the type written in the code, which the compiler sees: it is declared Item.
  • The runtime type is the class of the real object, known only while the program runs: Dish.
  • Dispatch means choosing which method body runs.
  • For it.price(), Java looks at the real object before the dot, at runtime: that's overriding, and it works.
  • For tax(it), the object is an argument, and Java chooses between overloads at compile time from the static type. There is no tax(Item), so: no suitable method found.
  • Choosing by just one runtime type (the receiver before the dot) is called single dispatch.
  • We want the method chosen by two types (the element's and the operation's): double dispatch.
  • Trick: put the item before the dot, and inside class Dish the word this has static type Dish.

4. The fix: accept and visit

import java.util.*;
interface Visitor<R> { R visit(Dish d); R visit(Drink d); R visit(Delivery d); }
interface Item { <R> R accept(Visitor<R> v); }                    // "let the visitor in"
record Dish(String name, int price) implements Item {
    public <R> R accept(Visitor<R> v) { return v.visit(this); } } // this is a Dish
record Drink(String name, int price) implements Item {
    public <R> R accept(Visitor<R> v) { return v.visit(this); } } // this is a Drink
record Delivery(int price) implements Item {
    public <R> R accept(Visitor<R> v) { return v.visit(this); } } // this is a Delivery
class TaxVisitor implements Visitor<Double> {                     // operation 1: GST
    public Double visit(Dish d)     { return d.price() * 0.05; }  // food: 5%
    public Double visit(Drink d)    { return d.price() * 0.18; }  // drinks: 18%
    public Double visit(Delivery d) { return d.price() * 0.18; }  // fee: 18%
}
public class Main {
    public static void main(String[] args) {
        List<Item> bill = List.of(new Dish("Thali", 200), new Drink("Cola", 50), new Delivery(40));
        double gst = 0;
        for (Item it : bill) gst += it.accept(new TaxVisitor());
        System.out.println("GST: " + gst);
    }
}

Output (real):

GST: 26.2

10 (thali) + 9 (cola) + 7.2 (delivery) = 26.2.

  • Visitor<R> has one visit per element type. R is a type parameter (episode 3): what the operation returns.
  • Every element has one tiny method: accept(v) { return v.visit(this); }. The line looks the same in every class but means something different in each, because this has a different static type.

Double dispatch, step by step

  1. it.accept(taxVisitor): the item is before the dot, so its runtime type picks Dish.accept. (Dispatch 1: by element.)
  2. Inside Dish.accept, v.visit(this): the visitor is before the dot, so its runtime type picks TaxVisitor; this is statically a Dish, so the compiler picked visit(Dish). (Dispatch 2: by operation.)
  3. 10.0 comes back.

Two ordinary calls, each dispatching on one type, together dispatch on both: that's double dispatch.

5. Payoff: a second operation with zero edits to the items

import java.util.*;
interface Visitor<R> { R visit(Dish d); R visit(Drink d); R visit(Delivery d); }
interface Item { <R> R accept(Visitor<R> v); }                    // "let the visitor in"
record Dish(String name, int price) implements Item {
    public <R> R accept(Visitor<R> v) { return v.visit(this); } } // this is a Dish
record Drink(String name, int price) implements Item {
    public <R> R accept(Visitor<R> v) { return v.visit(this); } } // this is a Drink
record Delivery(int price) implements Item {
    public <R> R accept(Visitor<R> v) { return v.visit(this); } } // this is a Delivery
class TaxVisitor implements Visitor<Double> {                     // operation 1: GST
    public Double visit(Dish d)     { return d.price() * 0.05; }  // food: 5%
    public Double visit(Drink d)    { return d.price() * 0.18; }  // drinks: 18%
    public Double visit(Delivery d) { return d.price() * 0.18; }  // fee: 18%
}
class ReceiptVisitor implements Visitor<String> {                 // operation 2: receipt
    public String visit(Dish d)     { return "  " + d.name() + "  Rs " + d.price(); }
    public String visit(Drink d)    { return "  " + d.name() + " (chilled)  Rs " + d.price(); }
    public String visit(Delivery d) { return "  Delivery fee  Rs " + d.price(); }
}
public class Main {
    public static void main(String[] args) {
        List<Item> bill = List.of(new Dish("Thali", 200), new Drink("Cola", 50), new Delivery(40));
        double gst = 0;
        for (Item it : bill) gst += it.accept(new TaxVisitor());
        for (Item it : bill) System.out.println(it.accept(new ReceiptVisitor()));
        System.out.println("GST: " + gst);
    }
}

Output (real):

  Thali  Rs 200
  Cola (chilled)  Rs 50
  Delivery fee  Rs 40
GST: 26.2

ReceiptVisitor is a new class. Dish, Drink and Delivery did not change by one character.

6. It has a name: the Visitor pattern

Role In our code Job
Visitor (interface) Visitor<R> Declares one visit per concrete element type
Concrete visitor TaxVisitor, ReceiptVisitor One operation, all its rules in one class
Element (interface) Item Declares accept(Visitor)
Concrete element Dish, Drink, Delivery accept calls v.visit(this)
Object structure the bill (List<Item>), or a tree The collection the visitor walks over
Client Main Picks a visitor and sends it over the elements

Intent (classic definition, via SourceMaking): "Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates."

      «interface»                         «interface»
      Visitor<R>  <-------- accepts ------  Item
   + visit(Dish): R                     + accept(Visitor<R>): R
   + visit(Drink): R                          ^
   + visit(Delivery): R                       | implements
          ^                            Dish   Drink   Delivery
          | implements                 accept: return v.visit(this)
   TaxVisitor   ReceiptVisitor

7. The cost: adding a new element type

import java.util.*;
interface Visitor<R> { R visit(Dish d); R visit(Drink d); R visit(Delivery d); R visit(Tip t); }
interface Item { <R> R accept(Visitor<R> v); }                    // "let the visitor in"
record Dish(String name, int price) implements Item {
    public <R> R accept(Visitor<R> v) { return v.visit(this); } } // this is a Dish
record Drink(String name, int price) implements Item {
    public <R> R accept(Visitor<R> v) { return v.visit(this); } } // this is a Drink
record Delivery(int price) implements Item {
    public <R> R accept(Visitor<R> v) { return v.visit(this); } } // this is a Delivery
record Tip(int price) implements Item { public <R> R accept(Visitor<R> v) { return v.visit(this); } } // NEW
class TaxVisitor implements Visitor<Double> {                     // operation 1: GST
    public Double visit(Dish d)     { return d.price() * 0.05; }  // food: 5%
    public Double visit(Drink d)    { return d.price() * 0.18; }  // drinks: 18%
    public Double visit(Delivery d) { return d.price() * 0.18; }  // fee: 18%
}
class ReceiptVisitor implements Visitor<String> {                 // operation 2: receipt
    public String visit(Dish d)     { return "  " + d.name() + "  Rs " + d.price(); }
    public String visit(Drink d)    { return "  " + d.name() + " (chilled)  Rs " + d.price(); }
    public String visit(Delivery d) { return "  Delivery fee  Rs " + d.price(); }
}
public class Main {
    public static void main(String[] args) {
        List<Item> bill = List.of(new Dish("Thali", 200), new Drink("Cola", 50), new Delivery(40));
        double gst = 0;    for (Item it : bill) gst += it.accept(new TaxVisitor());
        for (Item it : bill) System.out.println(it.accept(new ReceiptVisitor()));
        System.out.println("GST: " + gst);
    }
}

Output (real):

Main.java:11: error: TaxVisitor is not abstract and does not override abstract method visit(Tip) in Visitor
class TaxVisitor implements Visitor<Double> {                     // operation 1: GST
^
Main.java:16: error: ReceiptVisitor is not abstract and does not override abstract method visit(Tip) in Visitor
class ReceiptVisitor implements Visitor<String> {                 // operation 2: receipt
^
2 errors

Adding Tip means adding visit(Tip) to the interface, and then every visitor must be edited. As SourceMaking puts it, if the element classes change often, "keeping the Visitor subclasses in sync requires a prohibitive amount of effort." The good news: the compiler lists every place to fix (unlike the instanceof chain).

New operation New element type
Methods inside each class (normal OOP) Edit every class One new class
Visitor One new visitor class Edit every visitor

Think of a table: types down the side, operations across the top. Normal OOP keeps each row together (in the class); Visitor keeps each column together (in the visitor). Pick the one that matches how your code grows.

8. The classic home: abstract syntax trees

An abstract syntax tree (AST) is the tree a compiler builds from code: each node is one piece (a number, a +). "Abstract" because brackets and spaces are dropped; the tree's shape already says what belongs together. Node types almost never change, while tools keep adding operations: type checking, finding unused variables, generating code. Perfect for visitors.

interface Expr { <R> R accept(ExprVisitor<R> v); }                // one node of the tree
interface ExprVisitor<R> { R visit(Num n); R visit(Add a); R visit(Mul m); }
record Num(int value) implements Expr {                           // a leaf: just a number
    public <R> R accept(ExprVisitor<R> v) { return v.visit(this); } }
record Add(Expr left, Expr right) implements Expr {               // left + right
    public <R> R accept(ExprVisitor<R> v) { return v.visit(this); } }
record Mul(Expr left, Expr right) implements Expr {               // left * right
    public <R> R accept(ExprVisitor<R> v) { return v.visit(this); } }
class Eval implements ExprVisitor<Integer> {                      // operation 1: compute
    public Integer visit(Num n) { return n.value(); }
    public Integer visit(Add a) { return a.left().accept(this) + a.right().accept(this); }
    public Integer visit(Mul m) { return m.left().accept(this) * m.right().accept(this); }
}
class Show implements ExprVisitor<String> {                       // operation 2: print
    public String visit(Num n) { return String.valueOf(n.value()); }
    public String visit(Add a) { return "(" + a.left().accept(this) + " + " + a.right().accept(this) + ")"; }
    public String visit(Mul m) { return m.left().accept(this) + " * " + m.right().accept(this); }
}
public class Main {
    public static void main(String[] args) {
        Expr e = new Mul(new Add(new Num(2), new Num(3)), new Num(4));   // (2 + 3) * 4
        System.out.println(e.accept(new Show()) + " = " + e.accept(new Eval()));
    }
}

Output (real):

(2 + 3) * 4 = 20

Both visitors are recursive: visit(Add) sends the visitor further down with a.left().accept(this).

9. Modern Java: sealed interfaces + switch pattern matching

A sealed interface (episode 8) lists every class allowed to implement it with permits. Pattern matching for switch (episode 9): case Dish d -> checks the type and binds a variable of that type in one step.

import java.util.*;
sealed interface Item permits Dish, Drink, Delivery { }           // the full list of types
record Dish(String name, int price) implements Item { }
record Drink(String name, int price) implements Item { }
record Delivery(int price) implements Item { }
public class Main {
    static double tax(Item it) {                                  // an operation = one method
        return switch (it) {
            case Dish d     -> d.price() * 0.05;
            case Drink d    -> d.price() * 0.18;
            case Delivery d -> d.price() * 0.18;
        };                                                        // no default needed
    }
    public static void main(String[] args) {
        List<Item> bill = List.of(new Dish("Thali", 200), new Drink("Cola", 50), new Delivery(40));
        double gst = 0;
        for (Item it : bill) gst += tax(it);
        System.out.println("GST: " + gst);
    }
}

Output (real):

GST: 26.2

Delete the Delivery case:

import java.util.*;
sealed interface Item permits Dish, Drink, Delivery { }           // the full list of types
record Dish(String name, int price) implements Item { }
record Drink(String name, int price) implements Item { }
record Delivery(int price) implements Item { }
public class Main {
    static double tax(Item it) {                                  // an operation = one method
        return switch (it) {
            case Dish d     -> d.price() * 0.05;
            case Drink d    -> d.price() * 0.18;
        };                                                        // no default needed
    }
    public static void main(String[] args) {
        List<Item> bill = List.of(new Dish("Thali", 200), new Drink("Cola", 50), new Delivery(40));
        double gst = 0;
        for (Item it : bill) gst += tax(it);
        System.out.println("GST: " + gst);
    }
}

Output (real):

Main.java:8: error: the switch expression does not cover all possible input values
        return switch (it) {
               ^
1 error

Because the interface is sealed, the compiler knows every possible type and checks that the switch handles all of them: exhaustiveness. You get Visitor's safety without accept or visitor classes.

Classic Visitor Sealed interface + switch
Java version Any Java 21+ (switch patterns)
Elements need accept() in every class Nothing: plain data
New operation One visitor class One method with a switch
New element type Every visitor fails to compile Every switch fails to compile
Shared walking logic Can live in a base visitor Written in each method
Requirement None You own the whole hierarchy (it's sealed)

10. When to use it (and when not)

  • Use it: compilers and code tools (fixed node types, growing checks); exporting one document tree to HTML/PDF/JSON; reports over a stable model (tax, totals, audits); classes you're not allowed to edit.
  • Skip it: element types change often; a sealed switch is enough; there are only one or two operations.

Common mistakes

Mistake What you see Why Fix
instanceof chain per operation IllegalArgumentException: unknown item: Tip[name=Tip, price=30] Missing type found only at runtime Visitor, or a sealed switch
Overloads tax(Dish), tax(Drink) called with an Item error: no suitable method found for tax(Item) Overloads are picked from the static type accept() calls visit(this)
New element type, old visitors error: TaxVisitor is not abstract and does not override abstract method visit(Tip) in Visitor Every visitor needs the new method Add visit(Tip) to every visitor
Sealed switch missing a case error: the switch expression does not cover all possible input values Not exhaustive Handle every permitted type
Writing accept as v.visit((Item) this) or in a shared base class Wrong overload or compile error this must have the concrete type Write accept in each concrete class
Adding a default/fallback visit(Item) No error: new types silently ignored The compiler can no longer warn you Keep one visit per concrete type

Mini project: a calculator tree with three operations

Add a Sub node, then a third visitor that counts the nodes, without touching any node class for the new operation.

interface Expr { <R> R accept(ExprVisitor<R> v); }
interface ExprVisitor<R> { R visit(Num n); R visit(Add a); R visit(Sub s); R visit(Mul m); }
record Num(int value) implements Expr { public <R> R accept(ExprVisitor<R> v) { return v.visit(this); } }
record Add(Expr left, Expr right) implements Expr { public <R> R accept(ExprVisitor<R> v) { return v.visit(this); } }
record Sub(Expr left, Expr right) implements Expr { public <R> R accept(ExprVisitor<R> v) { return v.visit(this); } }
record Mul(Expr left, Expr right) implements Expr { public <R> R accept(ExprVisitor<R> v) { return v.visit(this); } }
class Eval implements ExprVisitor<Integer> {
    public Integer visit(Num n) { return n.value(); }
    public Integer visit(Add a) { return a.left().accept(this) + a.right().accept(this); }
    public Integer visit(Sub s) { return s.left().accept(this) - s.right().accept(this); }
    public Integer visit(Mul m) { return m.left().accept(this) * m.right().accept(this); }
}
class Show implements ExprVisitor<String> {
    public String visit(Num n) { return String.valueOf(n.value()); }
    public String visit(Add a) { return "(" + a.left().accept(this) + " + " + a.right().accept(this) + ")"; }
    public String visit(Sub s) { return "(" + s.left().accept(this) + " - " + s.right().accept(this) + ")"; }
    public String visit(Mul m) { return m.left().accept(this) + " * " + m.right().accept(this); }
}
class CountNodes implements ExprVisitor<Integer> {                 // a third operation: no node class changed
    public Integer visit(Num n) { return 1; }
    public Integer visit(Add a) { return 1 + a.left().accept(this) + a.right().accept(this); }
    public Integer visit(Sub s) { return 1 + s.left().accept(this) + s.right().accept(this); }
    public Integer visit(Mul m) { return 1 + m.left().accept(this) + m.right().accept(this); }
}
public class Main {
    public static void main(String[] args) {
        Expr e = new Mul(new Add(new Num(2), new Num(3)), new Sub(new Num(10), new Num(4)));
        System.out.println(e.accept(new Show()) + " = " + e.accept(new Eval()));
        System.out.println("nodes: " + e.accept(new CountNodes()));
    }
}

Output (real):

(2 + 3) * (10 - 4) = 30
nodes: 7

The tree has 7 nodes: Mul, Add, Num 2, Num 3, Sub, Num 10, Num 4.

Practice

1. Add a CaloriesVisitor to the bill: a thali is 750 kcal, other dishes 400, any drink 140, delivery 0.

Answer
import java.util.*;
interface Visitor<R> { R visit(Dish d); R visit(Drink d); R visit(Delivery d); }
interface Item { <R> R accept(Visitor<R> v); }                    // "let the visitor in"
record Dish(String name, int price) implements Item {
    public <R> R accept(Visitor<R> v) { return v.visit(this); } } // this is a Dish
record Drink(String name, int price) implements Item {
    public <R> R accept(Visitor<R> v) { return v.visit(this); } } // this is a Drink
record Delivery(int price) implements Item {
    public <R> R accept(Visitor<R> v) { return v.visit(this); } } // this is a Delivery
class TaxVisitor implements Visitor<Double> {                     // operation 1: GST
    public Double visit(Dish d)     { return d.price() * 0.05; }  // food: 5%
    public Double visit(Drink d)    { return d.price() * 0.18; }  // drinks: 18%
    public Double visit(Delivery d) { return d.price() * 0.18; }  // fee: 18%
}
class CaloriesVisitor implements Visitor<Integer> {               // operation 3: calories
    public Integer visit(Dish d)     { return d.name().equals("Thali") ? 750 : 400; }
    public Integer visit(Drink d)    { return 140; }
    public Integer visit(Delivery d) { return 0; }                // a fee has no calories
}
public class Main {
    public static void main(String[] args) {
        List<Item> bill = List.of(new Dish("Thali", 200), new Drink("Cola", 50), new Delivery(40));
        double gst = 0;
        for (Item it : bill) gst += it.accept(new TaxVisitor());
        System.out.println("GST: " + gst);
        int kcal = 0;
        for (Item it : bill) kcal += it.accept(new CaloriesVisitor());
        System.out.println("Calories: " + kcal);
    }
}

Output (real):

GST: 26.2
Calories: 890

2. Rewrite Eval for Num, Add, Mul as a sealed interface with a switch expression.

Answer
sealed interface Expr permits Num, Add, Mul { }
record Num(int value) implements Expr { }
record Add(Expr left, Expr right) implements Expr { }
record Mul(Expr left, Expr right) implements Expr { }
public class Main {
    static int eval(Expr e) {
        return switch (e) {
            case Num n -> n.value();
            case Add a -> eval(a.left()) + eval(a.right());
            case Mul m -> eval(m.left()) * eval(m.right());
        };
    }
    public static void main(String[] args) {
        Expr e = new Mul(new Add(new Num(2), new Num(3)), new Num(4));
        System.out.println(eval(e));
    }
}

Output (real):

20

3. Why can't Java pick tax(Dish) when you call tax(it) with Item it = new Dish(...)?

Answer

Overload resolution happens at compile time and uses the static type of the argument, Item. Only the receiver (the object before the dot) is dispatched by its runtime type. That's single dispatch.

4. Your app adds a new element type every week but only ever has two operations. Visitor or not?

Answer

Not. Visitor makes new element types expensive (every visitor changes). Put the two operations as methods in the classes (or use a sealed switch if the set is closed).

Quick quiz

static String f(Object o) { return "object"; }
static String f(String s) { return "string"; }

Object x = "chai";
System.out.println(f(x));

What is printed? (a) string (b) object (c) chai (d) Compile error

Answer

(b) object (real output). Overloads are chosen at compile time from the static type; x is declared Object. That's single dispatch, and it's why Visitor needs accept.

Interview questions

  1. What is the Visitor pattern? A behavioural pattern that moves an operation over a family of classes into a separate visitor object, so new operations can be added without changing those classes.
  2. What is double dispatch? Choosing the method by the runtime types of two objects. Visitor builds it from two single-dispatch calls: element.accept(visitor) then visitor.visit(this).
  3. Why does Java need it? Java dispatches only on the receiver's runtime type; overloads use the arguments' static types.
  4. Participants? Visitor, concrete visitor, element, concrete element, object structure, client.
  5. Main trade-off? New operations are cheap, new element types are expensive (every visitor changes).
  6. Where is it used? Compilers and ASTs, linters, document exporters, java.nio.file.FileVisitor style tree walks, reports over stable models.
  7. Visitor vs sealed types with pattern matching? Both give compile-time exhaustiveness; sealed switch needs modern Java and a hierarchy you control but no accept; Visitor works everywhere and can hold shared traversal logic.
  8. Visitor vs Strategy? Strategy swaps one algorithm for one object; Visitor applies one operation across many element types, with a method per type.
  9. Visitor vs Iterator / Composite? Composite builds the tree, Iterator walks it, Visitor does a type-specific job at each node; they're often used together.
  10. Does it break encapsulation? It can: visitors need access to elements' data, so elements may expose more accessors than otherwise.

Glossary

Term Meaning, with an example
Behavioural pattern A design pattern about how objects share work and talk to each other
Visitor pattern Put an operation over a family of classes into a separate visitor object, so new operations need no changes to those classes
Visitor An object that carries one operation to each element. TaxVisitor, the census officer
Concrete visitor One class implementing the visitor interface = one operation. ReceiptVisitor
Element A class the visitor works on. Dish, Drink, Delivery, a building
Concrete element A specific element class with its own accept
accept(visitor) The element's one method: "come in", implemented as return v.visit(this);
visit(...) The visitor's method for one element type: visit(Dish d)
Object structure The collection of elements being visited: a bill, a tree
Dispatch Choosing which method body runs for a call
Single dispatch Choosing the method by the runtime type of one object only, the receiver before the dot (Java's rule)
Double dispatch Choosing the method by the runtime types of two objects: the element and the visitor
Static type The declared type the compiler sees. In Item it = new Dish(...), Item
Runtime type The class of the actual object while running. Dish
Overloading Several methods with one name and different parameter types; chosen at compile time (episode 9)
Overriding A subclass replacing a method; chosen at runtime by the real object (episode 9)
instanceof Checks if an object is of a type: it instanceof Dish (episode 9)
Record A compact Java class for plain data: record Dish(String name, int price) (episode 3)
Type parameter A placeholder for a type, like R in Visitor<R> (episode 3)
Open-Closed Principle Code should be open for extension, closed for modification (episode 13)
Adding operations without changing classes Visitor's main benefit: a new visitor, no edits to the elements
Cost of adding new element types Visitor's price: every visitor needs a new visit method
Abstract syntax tree (AST) A tree of a program's pieces, without brackets and spaces. (2 + 3) * 4 = Mul(Add(2, 3), 4)
Node / leaf One element of a tree / a node with no children (Num)
Recursive A method that calls itself (directly or through accept) on smaller parts
Sealed interface An interface that lists every allowed implementation with permits (episode 8)
Pattern matching for switch case Dish d -> tests the type and binds d in one step (episode 9)
Exhaustiveness The compiler's check that a switch handles every possible type
Visitor vs sealed types with pattern matching Two ways to add operations outside the classes; see the comparison table
GST Goods and Services Tax, India's tax on goods and services
Census An official count of every household

Summary

  • Putting every operation in every class means editing them all each time; instanceof chains fail at runtime; overloads can't help because Java uses the static type (single dispatch).
  • Visitor: each element's accept calls visit(this), giving double dispatch; each operation is one visitor class.
  • New operations are cheap, new element types are expensive (the compiler lists every visitor to fix).
  • Its classic home is the AST: compilers and code tools.
  • In modern Java, a sealed interface + switch pattern matching gives the same exhaustiveness with less code.

Next episode: The Interpreter pattern: turn a little language, like a cafe's offer rules, into classes that can run it.