Implementing the visitor pattern
The visitor pattern is useful when you need to use different algorithms to apply to elements of a collection at different times. For example, you may have a collection of components of a train engine. Periodically, maintenance checks will need to be performed against each element. You may also want to occasionally display the status of each component. The collection does not necessarily change, only the operations performed against the components.
The visitor pattern is a way of structuring your data to facilitate the application of different algorithms against the structure without a new algorithm impacting the components.
The structure of the visitor pattern uses a base element interface or collection representing the collection of interest. For the train engine example, this base might represent the engine itself and its derived components will be elements such as wheels, engine, horn, and windows.
A visitor interface is added, which defines a visit
method...