When should you really use the visitor pattern

后端 未结 5 1253
谎友^
谎友^ 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 10:57

    I think the important thing is not how complex your hierarchy is, it is how fixed the hierarchy is.

    If your hierarchy is unlikely to change but the operations you want to perform on the classes is likely to change then you may have a candidate for the visitor pattern.

    It is all a compromise, so it is hard to draw a "line". You just need to decide which design will be more manageable in the long run given your requirements.

    For example, you may not want your Animal class to have lots of member functions like printToPDF(), getMigrationReport5(), etc and a visitor pattern would have been better.

    Or perhaps, you want to be able to easily add a Tortoise to your hierarchy of Animals without breaking any existing code. In which case the visitor pattern may not be such a good idea.

    There is a third option and that is to use some sort of pattern matching. But it is currently hard to do that elegantly in C++ without some external library.

提交回复
热议问题