Visitor
- Intent
- Move the operations on a stable group of classes into separate objects, so new operations can be added without touching those classes.
- Application
- A WOD mixes lifts, gymnastics and cardio, and every so often a new question about it shows up (equipment, calories, scaling…). Put each operation in its own object, without touching the element classes.
InstanceofAnalyzer, highlighted in red, asks each element whether it's a Lift or Gymnastics.
InstanceofAnalyzer, in red, and Cardio, highlighted: cardio's calories come out as 0 because its case doesn't exist.
The WorkoutVisitor interface appears, highlighted, with EquipmentVisitor and CalorieVisitor implementing it, next to the three element types.
Lift, highlighted together with EquipmentVisitor, calls it with visitLift(this).
Workout calls accept(v) on each element; Lift answers EquipmentVisitor, highlighted, which notes barbell and plates.
CalorieVisitor, highlighted, gets visitGymnastics and visitCardio from the elements.
The three element types, highlighted: a switch over the sealed interface covers them all.
POST /api/wods/analysis travels from the coach to the controller, which runs two visitors over Workout; Cardio accepts and CalorieVisitor adds 60 kcal. Workout and both visitors are highlighted.
Inside the Spring context, BeanDefinitionVisitor, highlighted, walks the definition: ${coach} becomes Ana and ${city} Madrid.
Final view: the coach, the controller, Workout, the three elements, both visitors and WorkoutVisitor, all inside the Spring context.
Step 1 of 10
Questions about a WOD
A WOD has elements of three types: lifts (deadlift, 100 kg × 15), gymnastics (30 burpees) and cardio (1000 m row). And the box keeps asking more questions about it: what equipment to set out, how many calories it burns, how to scale it…
The first version, InstanceofAnalyzer, answers each question with its own chain of instanceof: "is it a lift? is it gymnastics?…".
Step 2 of 10
Cardio got left out
Cardio came later. It was added to the equipment list, but in the calories chain nobody remembered to add it: a 1000 m row counts as 0 kcal, with no error or warning. The InstanceofAnalyzerTest test makes it plain.
Every new operation is one more chain to keep up to date, and the compiler doesn't warn when a case is missing.
Step 3 of 10
One method per type
Visitor defines an interface with one method per element type: visitLift, visitGymnastics, visitCardio, and result() to collect the result.
Each operation is a class that implements it. And since all three methods must be implemented, the compiler no longer lets you forget one.
Step 4 of 10
Each element calls its method
How does the visitor know what type of element it has without asking? It doesn't: the element tells it. Each one implements accept(visitor) by calling its own method: Lift calls visitLift(this).
It's a double call: the element's real class decides which method gets called (visitLift), and the visitor's real class decides which implementation runs. Together they replace the instanceof.
Step 5 of 10
One operation, one class
EquipmentVisitor gathers everything there is to know about equipment: barbell and plates for lifts, a pull-up bar if there are pull-ups or toes-to-bar, rower, bike or ski by machine.
Workout walks its elements and calls accept with the visitor; at the end it asks for result().
Step 6 of 10
Another operation, nothing touched
CalorieVisitor is another class with its three methods. Adding it didn't touch Lift, Gymnastics, Cardio or Workout. And the row can't be left out any more: without visitCardio, it doesn't compile.
Step 7 of 10
In modern Java
Since Java 21, a sealed interface and a switch with patterns give a similar safety net with less ceremony: the compiler knows every possible type and, if the switch has no default, it won't compile until you cover them all.
PatternMatchingCalories works out the same as CalorieVisitor, and a test checks it. In fact, in this code a switch over the sealed interface would have been enough not to forget cardio.
When does Visitor still pay off? When the hierarchy isn't sealed (or you can't use Java 21), when you want the operation to be an object you inject, pass around or swap, and when the structure drives the walk (a tree, a Composite) and the visitor receives each node.
Step 8 of 10
The analysis through the API
POST /api/wods/analysis with the WOD as JSON (a type field per element):
- Jackson creates
Lift,CardioandGymnastics, which validate their data. - The controller runs a new
EquipmentVisitorand a newCalorieVisitorover theWorkout(new because a visitor accumulates: reusing one would add everything twice). - The answer brings the equipment (barbell and plates, rower) and an estimated 102 kcal.
An element that breaks the rules, like a machine that doesn't exist, returns 400 with the reason.
Step 9 of 10
Spring already does it for you
A bean definition has many parts: the class name, the properties, the constructor arguments, nested beans and collections… BeanDefinitionVisitor walks all of them and runs every text value through a resolver.
That's what Spring uses to replace the ${...} in bean definitions (PropertySourcesPlaceholderConfigurer does it, through PlaceholderConfigurerSupport). In the test, ${coach} becomes "Ana" and ${city}, "Madrid". @Value("${...}") on fields, on the other hand, is resolved at injection time, not by this visitor.
It's a "loose" Visitor: the definition has no accept() and there's no double call, and there's a single walker; the operation you plug in is the resolver.
Step 10 of 10
Recap
You started with instanceof chains that forgot cardio and ended up with:
- One visitor per operation, with a method for each element type.
accept()on each element, calling its method without asking.- New operations without touching the elements, and forgotten cases that don't compile.
- The modern alternative:
sealedandswitchwith patterns.
Don't mix it up with its neighbours: Iterator walks the elements; Visitor says what to do with each type. Composite arranges elements in a tree, and a visitor can walk all of it. A Strategy changes how an operation is done; a visitor is a new operation over every type.
And when you don't need it: if element types change often, every new type means touching every visitor; and if there are few, simple operations, a method on each element or a switch over a sealed interface is more direct.
Code
InstanceofAnalyzer.java
public int calories(List<WorkoutElement> elements) {
int total = 0;
for (WorkoutElement e : elements) {
if (e instanceof Lift l) total += l.reps() * 2;
else if (e instanceof Gymnastics g) total += g.reps() * 2 / 5;
// Cardio was added later… and nobody remembered this chain
}
return total;
}InstanceofAnalyzer.java
public int calories(List<WorkoutElement> elements) {
int total = 0;
for (WorkoutElement e : elements) {
if (e instanceof Lift l) total += l.reps() * 2;
else if (e instanceof Gymnastics g) total += g.reps() * 2 / 5;
// Cardio was added later… and nobody remembered this chain
}
return total;
}WorkoutVisitor.java
/** The visitor: one method per kind of element. Each operation is one visitor; it accumulates, so one per walk. */
public interface WorkoutVisitor<R> {
void visitLift(Lift lift);
void visitGymnastics(Gymnastics gymnastics);
void visitCardio(Cardio cardio);
R result();
}Lift.java
@Override
public void accept(WorkoutVisitor<?> visitor) {
visitor.visitLift(this); // "I'm a Lift": the visitor runs its Lift code
}EquipmentVisitor.java
@Override public void visitLift(Lift lift) {
equipment.add("barbell + plates");
}
@Override public void visitGymnastics(Gymnastics g) {
String name = g.name().toLowerCase(java.util.Locale.ROOT);
if (name.contains("pull-up") || name.contains("toes-to-bar")) {
equipment.add("pull-up bar");
}
}
@Override public void visitCardio(Cardio c) {
switch (c.machine()) {
case "row" -> equipment.add("rower");
case "bike" -> equipment.add("assault bike");
case "ski" -> equipment.add("ski erg");
default -> { } // running needs no machine
}
}CalorieVisitor.java
@Override public void visitLift(Lift lift) { calories += lift.reps() * 2; }
@Override public void visitGymnastics(Gymnastics g) { calories += g.reps() * 2 / 5; }
@Override public void visitCardio(Cardio c) { calories += c.meters() * 6 / 100; }PatternMatchingCalories.java
public static int of(List<WorkoutElement> elements) {
int calories = 0;
for (WorkoutElement e : elements) {
calories += switch (e) { // no default: if a new kind appears,
case Lift l -> l.reps() * 2; // this stops compiling until it's handled
case Gymnastics g -> g.reps() * 2 / 5;
case Cardio c -> c.meters() * 6 / 100;
};
}
return calories;
}AnalysisApiTest.java
mvc.perform(post("/api/wods/analysis").contentType(MediaType.APPLICATION_JSON).content("""
[{"type":"lift","name":"deadlift","kg":100,"reps":15},
{"type":"cardio","machine":"row","meters":1000},
{"type":"gymnastics","name":"burpees","reps":30}]"""))
.andExpect(status().isOk())
.andExpect(jsonPath("$.equipment[1]").value("rower"))
.andExpect(jsonPath("$.calories").value(102));SpringDoesItTooTest.java
Map<String, String> config = Map.of("coach", "Ana", "city", "Madrid");
BeanDefinitionVisitor visitor = new BeanDefinitionVisitor( // visits class name, properties,
value -> value.startsWith("${") ? config.get(value.substring(2, value.length() - 1)) : value);
visitor.visitBeanDefinition(def); // constructor args, nested values…WorkoutVisitor.java
/** The visitor: one method per kind of element. Each operation is one visitor; it accumulates, so one per walk. */
public interface WorkoutVisitor<R> {
void visitLift(Lift lift);
void visitGymnastics(Gymnastics gymnastics);
void visitCardio(Cardio cardio);
R result();
}