When should you really use the visitor pattern

后端 未结 5 1256
谎友^
谎友^ 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条回答
  •  情歌与酒
    2021-02-06 11:07

    The Visitor pattern is for composing things. Basically that's when you use the visitor pattern: you have a non trivial operation which needs to compose primitive operation/properties and may need to adapt its behaviour depending on the type of value it works with. You'd put the primitive operations and properties in the class hierarchy itself, and extract the composition of those things into a visitor pattern type operation.

    Essentially the visitor pattern is a crutch for languages which lack 'true' polymorphism[1] and higher order functions. Otherwise you'd simply define the composition of operations as a higher order polymorphic function foo() that simply takes helper functions as parameters to resolve the specifics.

    So it's a limitation of the language more than a strength of design. If you use this sort of thing a lot to cut down on compilation times, you should consider whether you are trying to work against the tool or with the tool, i.e. whether you are doing the equivalent of a "real programmer who can program Fortran in any language". (And whether it is perhaps time to pick up/learn a different tool, besides the hammer.)

    1. By which I mean the ability of functions to work on values of "arbitrary types" without having to nail down the type to something specific (A or B), meaning the exact type/signature of the function/call changes depending on what you pass in.

提交回复
热议问题