Visitor

AKA: Walker

As you define more complicated Composites, you may need to walk their structure and operate on certain Composite or Leaf objects with your behaviour based on their type. In general, it’s considered poor etiquette to ask an object what type it is. This feature can be unavailable in some languages, such as C++, where run-time type information is optional.

Rather than look inside the object you want to react to, you ask each object to call you. When you traverse the Composite, each component will call into a specific method of the Visitor object provided to the traversal method. You create a concrete Visitor object which listens by overriding these methods.

Visitor

However, the visitor does not need to traverse a structure. The vital part of the pattern is the Accept method. The calling back from the visited object drives the type-specific callback into the visitor. You can see an example of traversal-free visiting in C++. There is an std::visit function that calls whichever method can bind to the visited variant.

It would have been better had the GoF book not started with the visitor attached to the process of structure traversal. Many developers were caught out by the structure walking and overlooked the significance of the type-based callback.

“For the sake of propriety, I’ll introduce myself.”