Cheatsheet

Visitor

Intent

Move the operations on a stable group of classes into separate objects, so new operations can be added without touching those classes.

Structure (UML)

Spring context×10LiftEquipmentVisitor«i»WorkoutVisitorAnalysisControllerWorkoutGymnasticsCalorieVisitorCardioCoach

Participants

  • Visitor (WorkoutVisitor), with one visit method per element type
  • ConcreteVisitor (EquipmentVisitor, CalorieVisitor), one operation each
  • Element (WorkoutElement), which accepts visitors with accept()
  • ConcreteElement (Lift, Gymnastics, Cardio), which call the visit for their type
  • Object structure (Workout), which walks its elements for any visitor

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();
}

Pros

  • A new operation is a new class; the elements don't change
  • All of an operation's code is together, not spread across the elements
  • The visitor can build up a result as it walks

Cons

  • A new element type means touching the interface and every visitor
  • accept() and the double call take some reading the first time
  • The elements have to expose what the visitors need
  • A visitor accumulates, so each walk needs a new one

← Visitor · Run it