Course contentsShow
← Software Engineering
Lesson 319 of 1,9339. Behavioral Design PatternsFree lesson

Double Dispatch in Visitor Pattern

Understand how Visitor uses double dispatch to select the correct method based on both visitor and element types.

Double Dispatch in Visitor Pattern

What you'll learn: How the Visitor pattern uses double dispatch to call the right method based on both the visitor type and the element type being visited.


The Double Dispatch Mechanism

In most object-oriented languages, method calls use single dispatch—the runtime system selects which method to execute based on the receiver object's type alone. For example, element.doSomething() picks the method based on what element is.

The Visitor pattern needs something more powerful: it must choose a method based on two types—the element being visited and the visitor itself. This is double dispatch.

How Double Dispatch Works

When you call element.accept(visitor):

  1. First dispatch: The runtime determines which accept method to call based on the element's actual type (e.g., ConcreteElementA or ConcreteElementB).

  2. Second dispatch: Inside that accept method, the element calls back to the visitor with visitor.visitConcreteElementA(this). Now the runtime selects the correct visit method based on the visitor's actual type.

This "ping-pong" ensures the right combination executes: the visitor tailored for that specific element type.

Why This Matters

Without double dispatch, you'd need messy instanceof checks or type casting. Double dispatch elegantly routes execution to the exact method designed for that visitor-element pair, keeping the code clean and type-safe.

Think of it like a restaurant: the waiter (visitor) approaches different tables (elements). Each table tells the waiter what it needs (first dispatch), then the waiter responds appropriately based on both the table type and their own role (second dispatch).

Key Takeaway: Double dispatch in the Visitor pattern uses two method calls—accept on the element and visit on the visitor—to select the correct operation based on both the visitor's type and the element's type, avoiding type checks and maintaining extensibility.