The visitor pattern is the last of the behavioral ones for us to review. This is going to feel similar to some others that allow us to abstract functionality such as a command. This one provides us with a way to group functionality and avoids duplication or even sprawl of our code.
The Visitor Pattern Defined
As always, we will start with the “Gang of Four” intent to set the stage for our discussion.
“Represent an operation to be perfomed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.”
Simply put, this pattern allows us to abstract and group functions that we will be performed on a collection of objects. It is almost like a compliment to an iterator. Instead of giving us objects from a collection (as an iterator does), this one goes to each object in the group. At each stop along the way, it performs an action or actions. A simple example is a print method. You can put a print method on every object and use an iterator to cycle through a collection so you can call that method. On the other hand, you can define the print method on the visitor object and give it a collection of objects to traverse and execute the action.
Applying The Pattern
This pattern ends up producing two potential hierarchies. One is to describe the node interface (the objects we will perform actions on). The other is the visitor hierarchy. A node can start as an interface with a way to progress to a next node. Then the visitor can perform an action or more as well as varied actions.
Java, PHP, C#, etc.
This pattern sticks to the core features of a language. All you need to implement this is a base class and inheritance. Therefore, the only differences among languages are going to be minor syntax variations to note what needs to be implemented or overridden in the child classes.