Visitor Pattern

Visitor Pattern is one of the behavioral design pattern which is used when we have to manage algorithms, relationships & responsibilities on a group of similar kind of objects at runtime, thus decoupling the operations from the object’s structure. So, Visitor pattern can provide additional functionality to a class without actually changing it.

The pattern should be used when you have distinct & unrelated operations to perform across a structure of objects. This avoids adding in code throughout your object structure that is better kept separate, so it encourages cleaner code. In summary, if you want to decouple some logical code from the elements that you’re using as input, visitor is probably the best pattern for the job.

On the downside, the arguments & return types for the visiting methods needs to be known in advance, so the Visitor pattern is not good for situations where these visited classes are subject to change. Every time a new type of Element is added, every Visitor derived class must be amended.

Also, it can be difficult to refactor the Visitor pattern into code that wasn’t already designed with the pattern in mind. And, when you do add your Visitor code, it can look obscure. The Visitor is powerful, but you should make sure to use it only when necessary.

Let’s try to illustrate the pattern with an example. Below is the class diagram for ease of reference –