Visitor Pattern
Put each operation over a fixed family of classes into its own visitor object, so new operations do not touch the classes.
Overview
The problem: many operations over a fixed set of types
An expression tree has a few node types: numbers, additions, multiplications. The program needs many operations on that tree: evaluate it, print it, count its nodes, check its types, simplify it. The obvious design adds one method per operation to every node class.
Picture that design as a grid. The rows are the node types, Num, Add and Mul; the columns are the operations, evaluate, print, count, typecheck and simplify. Every one of the 15 cells is a method, and each row lives in one node class.
Each new operation is a new column: one more method in every node class, and code for one concern (say, printing) scattered across three files. When the set of node types is stable and the set of operations keeps growing, that is the wrong way around. The Visitor pattern turns each column into one class.
Interview questions
- Show the smell Visitor fixes, and the fix.
- Explain double dispatch. Why does Visitor need two calls?
- When is Visitor the wrong choice?
- What happens when you add a new element type to a Visitor design?
- How does Visitor relate to Composite and Iterator?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio