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):
-
First dispatch: The runtime determines which
acceptmethod to call based on theelement's actual type (e.g.,ConcreteElementAorConcreteElementB). -
Second dispatch: Inside that
acceptmethod, the element calls back to the visitor withvisitor.visitConcreteElementA(this). Now the runtime selects the correctvisitmethod based on thevisitor'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.