Search code examples
visitor-pattern

What are advanteges and disadvantages of the Visitor behavior pattern?


I'm doing a presentation about the visitor design pattern, I understand how it works and all, but I've yet to find "defined" advantages and disadvantages, and I don't wanna speculate the advantages or disadvantages myself, since I could set false information.


Solution

  • Here are some of my thoughts on the Visitor pattern:

    Advantages:

    • Main advantage: adding an action to all your Elements is really easy as you only have to implement the Visitor interface. No need to modify every Element object to add an action.
    • You regroup actions common to many Elements in one single Visitor class. Only the code for that action is in that Visitor class. Makes the code easier to read if you want to know the code for one action specifically.

    Disadvantages:

    • Your Visitor can modify your Elements since an instance of the Element is sent to the Visitor. This is not recommended as it leads to side effects. This can be fixed by making your object immutable.
    • The code of the Element objects are spread out in all the Visitor objects. Therefore, the Element's logic lives in many classes. It makes the code harder to read if you want to look at the code for one Element object.
    • It necessitates one new Visitor class for every action.