When should you really use the visitor pattern

后端 未结 5 1302
谎友^
谎友^ 2021-02-06 10:29

Ok before marking this as a duplicate let me clarify myself. I\'m reading about the visitor pattern and its applicable uses.

I\'ve stumbled upon this post: When should I

5条回答
  •  Happy的楠姐
    2021-02-06 11:00

    When I've seen the Visitor pattern recommended on SO, it is nearly always in order to avoid type checking. The Visitor pattern is therefore applied to a small class hierarchy, particularly when every subclass can be listed out in code.

    Questions that lead to this pattern often start with, "I have a long chain of if-else statements where each condition tests for a different class from a hierarchy. How can I avoid so many if-else statements?"

    For example, say I have a scheduling application with a class called Day which has seven subclasses (one for each day of the week). The naïve approach would be to implement this scheduler using if-else or switch-case.

    // pseudocode
    if (day == Monday)
        // Monday logic
    else if (day == Tuesday)
        // Tuesday logic
    // etc.
    

    The Visitor pattern avoids this chain of conditional logic by taking advantage of double dispatch. The seven days become seven methods, with the appropriate method chosen at runtime based on the type of Day argument which is passed.

    Note that neither the Visitor pattern nor any other GoF pattern is used to decrease compilation time. Modifying any pre-existing interface can be difficult and error-prone. The Visitor pattern allows new type-based functionality to be added without modifying existing classes.

提交回复
热议问题